【问题标题】:How to solve "Expected a value of type 'int', but got one of type 'String'" in Flutter如何在 Flutter 中解决“期望一个‘int’类型的值,但得到一个‘String’类型的值”
【发布时间】:2020-11-12 07:52:57
【问题描述】:

我有一个本地 JSON 文件,如下所示:

[
    {
        "1": [
            {
                "mode": "text",
                "value": "text exapple1"
            },
            {
                "mode": "latex",
                "value": "\frac00"
            },
            {
                "mode": "text",
                "value": "text exapple2"
            },
            {
                "mode": "latex",
                "value": "\frac00"
            },
            {
                "mode": "text",
                "value": "text exapple3"
            }
        ]
    },
    {
        "2": [
            {
                "mode": "text",
                "value": "text exapple4"
            }
        ]
    }
]

我正在尝试在我的代码中使用 FutureBuilder 解析它:

return FutureBuilder(
    future:
        DefaultAssetBundle.of(context).loadString("assets/paragraph.json"),
    builder: (context, snapshot) {
      var mydata = json.decode(snapshot.data.toString());
      if (mydata != null) {
        return SizeTransition(
            axis: Axis.vertical,
            sizeFactor: animation,
            child: Center(child: Text(mydata["1"][0].toString()))
            );
      } else {
        return SizeTransition(
            axis: Axis.vertical,
            sizeFactor: animation,
            child: Center(child: CircularProgressIndicator())
            );
      }
    });

这是我收到的错误消息:

══╡ 小部件库发现异常 ╞═════════════════════════════════════════════════ ══════════ 下面的 TypeErrorImpl 被抛出构建 FutureBuilder(脏,状态: _FutureBuilderState#4fb8d): 需要一个“int”类型的值,但得到一个“String”类型的值

如果我这样做:

mydata[1][1]

它给了我一个空输出!

这段代码有什么问题以及如何修复它?

【问题讨论】:

  • 这是一个包含地图的列表,因此请尝试将其称为mydata[0]["1"].toString()

标签: flutter dart


【解决方案1】:

您的 JSON 在顶层代表一个数组,因为它以 [ 开头。因此,您必须使用整数索引而不是字符串来访问元素。在第二级,您有地图对象。所以我认为mydata[2]["2"]["mode"] 应该给你“文本”。或者您希望使用特定访问从您的 JSON 输出什么?

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2021-11-26
    • 2022-12-05
    • 2021-12-27
    • 2021-03-16
    • 2022-01-08
    • 2021-09-13
    • 2021-09-18
    • 2020-12-03
    相关资源
    最近更新 更多