Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter SharedPreferences value to Provider on applcation start

Tags:

flutter

dart

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

like image 513
aknd Avatar asked Aug 26 '19 17:08

aknd


2 Answers

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();
  }
  ......
}
like image 192
aknd Avatar answered Nov 15 '22 09:11

aknd


// 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
}
like image 37
CopsOnRoad Avatar answered Nov 15 '22 11:11

CopsOnRoad