首页 > 解决方案 > Flutter SharedPreferences 值在应用程序开始时提供给 Provider

问题描述

我正在尝试在应用程序启动时设置从 sharedpreferences 到 provider 的值。

这是我到目前为止所拥有的,对小部件的 sharedpreferences 正在工作: https ://gist.github.com/andraskende/a19c806aeef0ce88e9a9cafa49660ab4#file-main-dart-L211-L223

标签: flutterdart

解决方案


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();
  }
  ......
}

推荐阅读