如何立即从共享首选项中检索值? - 颤动

how to retrieve a value from shared preferences instantly? - FLUTTER

我正在尝试将页面显示为初始登录,这仅在我的开关值设置为 true 时显示。 开关值与共享首选项一起存储,但是当我打开应用程序时它没有恢复,只有在应用程序更新后它才真正恢复。我怎样才能在我打开我的应用程序时立即恢复它?

代码下方:

Future<bool> saveSwitchState(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("switched", value);
    print('Switch Value saved $value');
    return prefs.setBool("switched", value);
  }

Future<bool> getSwitchState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    SettingsPage.switched = prefs.getBool("switched")!;
    print(SettingsPage.switched);

    return SettingsPage.switched;
  }

在另一页则实际恢复的值:

if(AuthPage.authenticated == false && SettingsPage.switched == true ) {
      yield ProfileNoAuth();
      return; }

您可以按照以下步骤使用依赖注入: get it package

创建一个单独的飞镖,其中包含如下代码文件:

GetIt locator = GetIt.instance;
Future<void> setupLocator() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
locator.registerLazySingleton<SharedPreferences>(() => sharedPreferences);  
}

调用 setupLocator() 方法并在主函数中等待它

 void main() async {
    await setupLocator();
    runApp(App());
    }

像这样从任何地方访问 SharedPreferences 实例: 定位器(); 现在是 SharedPreferences 实例(如果项目中的任何地方都可用) 请注意,您不必再等待获取实例,因为您只有一个实例可跨应用程序共享

    bool getSwitchState() {
    final prefs = locator<SharedPreferences>();
    SettingsPage.switched = prefs.getBool("switched")!;
    print(SettingsPage.switched);

    return SettingsPage.switched;
   }