【问题标题】:Flutter:Instance of 'SharedPreferences'Flutter:“SharedPreferences”的实例
【发布时间】:2020-09-07 11:32:50
【问题描述】:

我在 Flutter 应用程序中使用 shared_preferences 插件,我想在用户选择城市时保存数据。 但是当我尝试打印时,它只是说;

“SharedPreferences”未处理异常的实例:setState() 回调参数返回一个 Future

。 (即使我删除了我的 setState 部分,我也会在我的控制台中得到同样的错误)。

有人知道原因吗?

卡片小部件中的我的文字

 Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 8.0),
                                child: Text(
                                  snapshot.data.name,
                                  style: TextStyle(fontSize: 16),
                                ),
                              ),

当点击我保存它的位置时

   onTap: () {
                            setState(() async {
                              final country =
                                  await SharedPreferences.getInstance();
                              String name;
                              name=snapshot.data.name;
                              country.setString('name', name);
                              print('here $country');
                          
                            });
                          },

【问题讨论】:

    标签: flutter sharedpreferences


    【解决方案1】:

    试试

     onTap: () async {
      final country =
          await SharedPreferences.getInstance();
      setState(() {
      String name;
      name=snapshot.data.name;
      country.setString('name', name);
      print('here $name);
    
      });
    },
    

    【讨论】:

    • 为了给这个答案添加一些解释,setState 的回调不能是异步的。这在文档中提到:api.flutter.dev/flutter/widgets/State/setState.html
    • 这次它只写了 'SharedPreferences' 的实例
    • 不明白你的意思?你能解释一下吗?
    • 不,我的意思是当我编写你所说的解决方案时没有任何改变。我的控制台上仍然有相同的输出,它只显示“SharedPreferences”的此处实例不再
    • 能否重新启动应用程序并重新运行应用程序
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2018-08-30
    • 1970-01-01
    • 2023-02-19
    • 2020-07-03
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多