我有一个本地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/