Can't Initialize Async SharedPreferences Class via Constructor

1,065 views
Skip to first unread message

Matthew Jones

unread,
Mar 14, 2019, 4:57:19 PM3/14/19
to Flutter Dev
I'm attempting to use this package:

Here's my code:

import 'package:shared_preferences/shared_preferences.dart';


class SharedPreferencesProvider {
 
SharedPreferences prefs;


 
SharedPreferencesProvider() {
    init
();
 
}


 
// Get get instance of SharedPreferences upon instantiation.
 
void init() async {
    prefs
= await SharedPreferences.getInstance();
 
}


 
// Save some data
 
void saveData() {
      prefs
.setString('key', 'value');
 
}
}


When I run this, I get an error stating that setString was called on null. I did some investigating, and it appears that the prefs property is never actually initiated. It really is null when called by saveData(). 

I'm guessing this has to do with async operations in Dart and the way constructors work, but I'm not sure how to get around it. How can I initialize my prefs property so I can utilize it across my class?

Matthew Jones

unread,
Mar 14, 2019, 5:15:09 PM3/14/19
to Flutter Dev

Steven McDowall

unread,
Mar 14, 2019, 6:23:29 PM3/14/19
to Matthew Jones, Flutter Dev
You need to await the init() call since it’s also asynchronous 
--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages