How to use SharedPreferences and Injectable in Flutter?

1,576

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());
}

To actually use:

final prefs = getIt<SharedPreferences>();
await prefs.setString('city', city);

NOT:

final module = getIt<InjectionModule>();
module.prefs.setString('test', test);

Note differences between SharedPreferences and InjectionModule.

Share:
1,576
Silver Qui.
Author by

Silver Qui.

Updated on December 20, 2022

Comments

  • Silver Qui.
    Silver Qui. over 1 year

    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());
    }
    
  • Martin Berger
    Martin Berger about 2 years
    Just do remember to use it like this: final prefs = getIt<SharedPreferences>(); await prefs.setString('city', city); .... not getIt< InjectionModule >()