'Future <dynamic>'不是'String'类型的子类型

时间:2020-04-28 20:01:43

标签: flutter sharedpreferences future

我是陌生人。我尝试学习SharedPreferences,但有这个例外。 我该如何解决?

_MyAppState类扩展了状态{

 Future<SharedPreferences> prefs = SharedPreferences.getInstance(); 
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Column(
              children: <Widget>[
                RaisedButton(
                  onPressed: () {addStringToSF();},
                ),
                Text(getStringValuesSF()),
              ],
            ),


        );
      }

      addStringToSF() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('stringValue', "abc");
      }

     getStringValuesSF() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String stringValue = prefs.getString('stringValue');
        return stringValue;
      }
    }

1 个答案:

答案 0 :(得分:1)

默认异步函数返回动态,我们必须进行类型转换

Future<String> getStringValuesSF() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String stringValue = prefs.getString('stringValue');
        return stringValue;
      }