flutter - 如何解决 “Expected a value of type ' int',但在Flutter中得到了 'String'类型之一

标签 flutter dart

我有一个本地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())
            );
      }
    });
这是我收到的错误消息:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following TypeErrorImpl was thrown building FutureBuilder(dirty, state: _FutureBuilderState#4fb8d): Expected a value of type 'int', but got one of type 'String'


如果我这样做:
mydata[1][1]
它给了我一个空输出!
该代码有什么问题以及如何解决?

最佳答案

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

关于flutter - 如何解决 “Expected a value of type ' int',但在Flutter中得到了 'String'类型之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63039837/

相关文章:

list - Dart 如何克隆 map 列表

android - 如何在加载数据之前在flutter中显示进度条

flutter - 警告 : the 'flutter' tool you are currently running is not the one from the current directory

class - 是否可以在 Dart 的类中将方法声明为 final?

list - 实现 list 的更快方法?

flutter如何比较两个不同格式的电话号码

flutter - 如果存在具有同名方法的 Mixin,如何调用父类(super class)方法

dart - 在 GestureDetector 中滚动 ListView

flutter - 单独的窗口小部件文件中的Flutter DropdownMenuItem

android - 在Flutter应用程序中向 map 框添加标记