【问题标题】:Flutter SharedPreferences type 'String' is not a subtype of type 'List<Object>'Flutter SharedPreferences 类型“String”不是“List<Object>”类型的子类型
【发布时间】:2020-05-03 23:37:19
【问题描述】:

我想要做的是获取 SharedPreferences stringList 但发生异常。我正在尝试解决它但被卡住了(我是菜鸟)。这是代码:

  List<String> name;

  getName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.containsKey("name")) {
      name = prefs.getStringList("name");
    }
    return [];
  }

  @override
  void initState() {
    this.getName();
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    return name.isEmpty
        ? Container(
            color: Colors.white,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset("assets/no-data.png"),
                  Text("No Seeds Saved", style: TextStyle(fontSize: 20))
                ],
              ),
            ),
          )
        : ListView.builder(
            itemCount: name.length,
            itemBuilder: (context, index) {
              final item = name[index];
              return Container(
                padding: EdgeInsets.all(8),
                child: Card(
                  color: Colors.teal[600],
                  child: ListTile(
                    title: Text(item,
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold)),

                    trailing: IconButton(
                        icon: Icon(Icons.remove_circle,
                            color: Colors.redAccent[400]),
                        onPressed: () {}),
                  ),
                ),
              );
            },
          );
  }

发生了异常。 _TypeError(类型'String'不是类型'List'的子类型)

在构建 _BodyBuilder 时引发了以下 _TypeError: “Future”类型不是“List”类型的子类型

你能帮帮我吗?

【问题讨论】:

  • 请同时显示您使用返回值的代码
  • 好吧,编辑好了,我只在其他地方的小部件构建上使用它,这是问题吗?我使用它的方式或其他方式。我想不通
  • @YouOne 你能显示你保存列表的代码吗?
  • 编辑过的朋友看看。对不起,我的代码很乱
  • 是不是因为在我更改为 List 之前,我使用 String 来存储具有相同键(“名称”)的值。我是共享首选项的新手,是这样吗?我不确定

标签: flutter sharedpreferences


【解决方案1】:

自己解决了这个问题,是因为我没有正确声明我的变量,而且我也没有调用 setState 本身。这就是我改变的地方

List<String> name = [];
  getName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.containsKey("name")) {
      setState(() {
        name.addAll(prefs.getStringList("name"));
      });
    }
  }

我只是把它留在这里,以防有人遇到同样的问题xD

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2021-07-10
    • 2021-09-30
    • 2022-12-02
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多