首页 > 解决方案 > Flutter:“SharedPreferences”的实例

问题描述

我在我的 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');
                          
                            });
                          },

标签: fluttersharedpreferences

解决方案


尝试

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

  });
},

推荐阅读