Flutter - How to get value from shared preferences in a non-async method

前端 未结 2 594
陌清茗
陌清茗 2021-02-13 17:34

I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Futu

相关标签:
2条回答
  • 2021-02-13 17:44

    You can use FutureBuilder()

    SharedPreferences sharedPrefs;
    
    @override
    Widget build(BuildContext context) {
      return FutureBuilder(
        future: _getPrefs(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return YourFinalWidget();
          }
          return CircularProgressIndicator(); // or some other widget
        },
      );
    }
    
    Future<void> _getPrefs() async{
      sharedPrefs = await SharedPreferences.getInstance();
    }
    
    0 讨论(0)
  • 2021-02-13 18:10

    You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()

    SharedPreferences sharedPrefs;
    
    @override
    void initState() {
      super.initState();
      SharedPreferences.getInstance().then((prefs) {
        setState(() => sharedPrefs = prefs);
      });
    }
    
    0 讨论(0)
提交回复
热议问题