Reputation: 843
I'm trying to to set a value from sharedpreferences to provider at application start.
this what I have so far, sharedpreferences to widget is working: https://gist.github.com/andraskende/a19c806aeef0ce88e9a9cafa49660ab4#file-main-dart-L211-L223
Upvotes: 8
Views: 6663
Reputation: 267524
// global variable, that can be accessed from anywhere
SharedPreferences sharedPrefs;
void main() async { // make it async
WidgetsFlutterBinding.ensureInitialized(); // mandatory when awaiting on main
sharedPrefs = await SharedPreferences.getInstance(); // get the prefs
// do whatever you need to do with it
runApp(MyApp()); // rest of your app code
}
Upvotes: 5
Reputation: 843
Finally i figured out with trial and error... It can be done in the constructor as:
class BarcodeProvider with ChangeNotifier {
BarcodeProvider() {
setup();
}
void setup() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String url = (await prefs.getString('url') ?? '');
_url = url;
notifyListeners();
}
......
}
Upvotes: 14