简体   繁体   中英

How to use SharedPreferences and Injectable in Flutter?

Im using the library Injectable for Dependency Injection in flutter but Im getting a error where I cannot use SharedPreferences.

Error: Exception has occurred. FlutterError (ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. If you're running a test, you can call the TestWidgetsFlutterBinding.ensureInitialized() as the first line in your test's main() method to initialize the binding.) I've tryed creating a class and put @lazySingleton

  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

and I tryed to put WidgetsFlutterBinding.ensureInitialized()

void main() { 
  WidgetsFlutterBinding.ensureInitialized();
  configureInjection(Environment.prod);
  runApp(MyApp());
}

you can pre-await the future in SharedPreference by annotating with @preResolve

@module
abstract class InjectionModule {

//injecting third party libraries
   @preResolve
   Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}

and on the configureInjection class

final GetIt getIt = GetIt.instance;

@injectableInit
Future<void> configureInjection(String env) async {
 await $initGetIt(getIt, environment: env);
}

and also on the main class

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 await configureInjection(Environment.prod);
 runApp(MyApp());
}

Below is the way i got it to work, no guarantee it's the best method.

Await the configureInjection method in the main method.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await configureInjection(Env.prod);
  runApp(App());
}

And wrap you app in FutureBuilder that makes use of getIt.allReady().

Widget build(context) {
  return FutureBuilder(
    future: getIt.allReady(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        // ... your app widgets
      } else {
        // ... some progress indicator widget
      }
    }
  );
}

Helpfull links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM