How to use SharedPreferences and Injectable in Flutter?
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
.
Silver Qui.
Updated on December 20, 2022Comments
-
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 theWidgetsFlutterBinding.ensureInitialized()
first. If you're running a test, you can call theTestWidgetsFlutterBinding.ensureInitialized()
as the first line in your test'smain()
method to initialize the binding.) I've tryed creating a class and put @lazySingletonFuture<SharedPreferences> get prefs => SharedPreferences.getInstance();
and I tryed to put WidgetsFlutterBinding.ensureInitialized()
void main() { WidgetsFlutterBinding.ensureInitialized(); configureInjection(Environment.prod); runApp(MyApp()); }
-
Martin Berger about 2 yearsJust do remember to use it like this: final prefs = getIt<SharedPreferences>(); await prefs.setString('city', city); .... not getIt< InjectionModule >()