I woudl like to initialize a private SharedPreferences field and seems a good place for it is using a constructor. But as long as SharedPreferences.getInstance()
returns a Future a compiler can not use await because of The await expression can only be used in an async function.
. Otherwise it is impossible to make the constructor body as async. So how to make it?
GetIt getIt = GetIt.instance;
void setupLocator() {
getIt.registerSingleton<LocalStorageService>(LocalStorageService());
}
class LocalStorageService {
SharedPreferences _prefs;
LocalStorageService() : _prefs = await SharedPreferences.getInstance(); //error
...
}
It is possible to make an additional function to call the setupLocator()
and make it async
and then use it inside main() method awaiting a result and passing an instance of SharedPreferences into constructor of LocalStorageService
as an argument, but I would prefer to initialize it inside the LocalStorageService
class.
CodePudding user response:
You should check this question: Calling an async method from component constructor in Dart
I think you can do something like this - just keep in mind your _prefs would not be available immediately after the object is created.
GetIt getIt = GetIt.instance;
void setupLocator() {
getIt.registerSingleton<LocalStorageService>(LocalStorageService());
}
class LocalStorageService {
SharedPreferences _prefs;
LocalStorageService() : SharedPreferences.getInstance().then((prefs) => _prefs=prefs);
...
}
CodePudding user response:
Since you are using GetIt
, I suggest you to use registerSingletonAsync
method
getIt.registerSingletonAsync<LocalStorageService>(() async {
final pref = await SharedPreferences.getInstance();
return LocalStorageService(pref);
});
I personally don't like creating it in a constructor since maybe another class is dependent on it and it will get a null variable before constructing and it will cause problems.