如何解决 Flutter 中“期望一个‘int’类型的值,但得到一个‘String’类型的值”

Ami*_*ani 4 dart flutter

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

\n
[\n    {\n        "1": [\n            {\n                "mode": "text",\n                "value": "text exapple1"\n            },\n            {\n                "mode": "latex",\n                "value": "\\frac00"\n            },\n            {\n                "mode": "text",\n                "value": "text exapple2"\n            },\n            {\n                "mode": "latex",\n                "value": "\\frac00"\n            },\n            {\n                "mode": "text",\n                "value": "text exapple3"\n            }\n        ]\n    },\n    {\n        "2": [\n            {\n                "mode": "text",\n                "value": "text exapple4"\n            }\n        ]\n    }\n]\n
Run Code Online (Sandbox Code Playgroud)\n

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

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

这是我收到的错误消息:

\n
\n

\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1 小部件库捕获异常\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\ x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\ x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\ x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\ x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n以下 TypeErrorImpl 被抛出构建\nFutureBuilder(脏,状态:\ n_FutureBuilderState#4fb8d):\n需要“int”类型的值,但得到“String”类型的值

\n
\n

如果我这样做:

\n
mydata[1][1]\n
Run Code Online (Sandbox Code Playgroud)\n

它给了我一个空输出!

\n

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

\n

jmi*_*izv 5

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