7

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?

OMi Shah
  • 5,768
  • 3
  • 25
  • 34
Vasiliy
  • 16,221
  • 11
  • 71
  • 127
  • instead of initializing shared pref in the main method can't you do the same later? – OMi Shah Jul 25 '21 at 08:41
  • @OMiShah I want to initialize this object just once, and then pass a reference around. If there is a way to do that in MyApp, then it's also alright. However, I don't want to initialize SharedPreferences in all widgets that will require this feature. – Vasiliy Jul 25 '21 at 08:50
  • I had to make an edit to change my vote from negative since I made that by mistake. never mind :P – OMi Shah Jul 25 '21 at 09:06

1 Answers1

8

add this before you preference instance

 WidgetsFlutterBinding.ensureInitialized();
Dali Hamza
  • 568
  • 1
  • 4
  • 8
  • This works! Thanks. Any side effects of this call that I need to be aware of? – Vasiliy Jul 25 '21 at 08:57
  • 2
    that just initialize futter context for methodChannel becuase preference in flutter use native code also you can used in the test if you want to initialize things before runApp or testWidget you should add that line – Dali Hamza Jul 25 '21 at 09:07
  • I am having the same issue. Even though I put this line still getting instance issue. – Qaiser Hussain Feb 03 '23 at 15:26