Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: pause code execution to initialize SharedPreferences on startup

Tags:

flutter

I read other answers about initializing SharedPreferences in Flutter app (e.g. this one), but I want to take another route: initialize SharedPreferences object once at the very beginning, and then just pass it around to specific clients as required (a.k.a. dependency injection).

I tried to make my main method async and then use await:

void main() async {
  var prefs = await SharedPreferences.getInstance();
  runApp(MyApp(prefs));
}

Intuitively, I expected that the execution will halt until prefs is initialized, and then proceeds to runApp. Unfortunately, I get a white screen instead of my UI, so I guess I'm missing something here.

I also tried to use then:

void main() async {
  SharedPreferences.getInstance().then((prefs) => runApp(MyApp(prefs)));
}

Same result: white screen.

Is there a way to initialize SharedPreference in this manner in Flutter?

like image 924
Vasiliy Avatar asked Jul 24 '21 12:07

Vasiliy


Video Answer


1 Answers

add this before you preference instance

 WidgetsFlutterBinding.ensureInitialized();
like image 148
Dali Hamza Avatar answered Nov 11 '22 05:11

Dali Hamza