首页 > 解决方案 > 在应用程序启动时使用 Provider 的 SharedPreferences

问题描述

我有 2 个启动页面,如果我在共享首选项的“登录”下没有任何值,我想运行 PgStartupNew。但我不能这样做,因为 SharedPreferences 还没有初始化。我怎样才能解决这个问题?

主要.dart

        class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            // Provider<Future>(create: (_) => Future.value(42)),
            Provider<MySharedPreferences>(
                create: (_) => MySharedPreferences.create()),
            Provider<User>(create: (_) => User.create()),
          ],
          child: MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: MyStyle.getThemeData(),
            title: 'TestApp',
            home: PgSelectStartup(),
          ),
        );
      }
    }
    
    class PgSelectStartup extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return (Provider.of<MySharedPreferences>(context).read("login") ==
                null)
            ? PgStartupNew()
            : PgStartupLogin();
      }
    }

my_shared_preferences.dart

 String? read(String key) {
    return prefs.getString(key) ?? null;
  }

错误:

════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building PgSelectStartup(dirty, dependencies: [_InheritedProviderScope<MySharedPreferences>]):
The method 'getString' was called on null.
Receiver: null
Tried calling: getString("login")

我尝试在从构建返回之前添加一个额外的调用 read() 方法并尝试强制重新初始化 SharedPrefs,但它仍然无法正常工作。在类 PgSelectStartup 中对 read() 的每次调用都失败,因为 prefs == null。我该如何解决?当 prefs 已经初始化时如何使用“Widget build(BuildContext context)”?我发现了一些如何做到这一点的案例,但在我的案例中没有一个工作,我在启动时使用 SharedPrefs,而且通过 MultiProvider 使用它

标签: flutterflutter-provider

解决方案


如果您想在启动时访问共享首选项,您需要在runApp调用之前对其进行初始化main


await MySharedPreferences.create();
// Initialize all needed asynchronous singletons.

runApp(MyApp());

或使用FutureBuilder


推荐阅读