I have 2 startup page, I want run PgStartupNew if I haven't any value under "login" in shared preferences. But I can't do this, because SharedPreferences is not init yet. How I can avid this problem?
main.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;
}
Error:
════════ 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")
I try add one extra call read() method before return from build and try force reinit SharedPrefs, but it still not working. EVERY first call to read() in class PgSelectStartup failing, because prefs == null. How I can fix it? How to use "Widget build(BuildContext context)" when prefs is already init? I found some cases how to do it, but none working in my case, where I use SharedPrefs on startup, and moreover using it via MultiProvider
If you want to access shared preferences at start up you need to either initialize it before runApp
is invoked in main
:
await MySharedPreferences.create();
// Initialize all needed asynchronous singletons.
runApp(MyApp());
or use FutureBuilder