flutter - 在应用程序启动时使用 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 使用它
解决方案
如果您想在启动时访问共享首选项,您需要在runApp
调用之前对其进行初始化main
:
await MySharedPreferences.create();
// Initialize all needed asynchronous singletons.
runApp(MyApp());
推荐阅读
- unity3d - 如何修复 ARCore 可以同时显示的预制件数量?(带图像识别)
- arrays - JSON数组Angular 6的比较
- microsoft-graph-api - 如何使用 Microsoft Graph API 检索其他用户的 MS Teams 聊天?
- python - pysnmp 中的异步代码未按预期响应
- python - google.api_core.exceptions.PermissionDenied:403 打开文件时出错
- javascript - 在类javascript类构造函数中使用异步调用
- javascript - 调用 model.discriminator() 时是否会传递虚拟变量?
- python - Keras 的 ImageDataGenerator 中的剪切究竟是做什么的?
- mongodb - $match 在 mongodb 中使用 _id 进行聚合是一个对象
- python - 将多个 csr_matrix 馈送到 tensorflow 中的 feed_dict