Flutter 如何解决;应为类型为';int';,但是得到了一个类型';字符串'&引用;飘飘然
我有一个本地JSON文件,如下所示:Flutter 如何解决;应为类型为';int';,但是得到了一个类型';字符串'&引用;飘飘然,flutter,dart,Flutter,Dart,我有一个本地JSON文件,如下所示: [ { "1": [ { "mode": "text", "value": "text exapple1" }, { "mode": "la
[
{
"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())
);
}
});
以下是我收到的错误消息:
══╡ WIDGETS库捕获到异常
╞═══════════════════════════════════════════════════════════
以下TypeErrorImpl被抛出到建筑中
FutureBuilder(脏,状态:
_FutureBuilderState(4fb8d):
应为“int”类型的值,但得到的却是“String”类型的值
如果我这样做:
mydata[1][1]
它给我一个空输出
这个代码有什么问题以及如何修复它?您的JSON在顶层代表一个数组,因为它以
[
开头。因此您必须使用整数索引而不是字符串访问元素。在第二层,您有映射对象。因此我认为mydata[2][“2”[“mode”]
应该为您提供“文本”。或者,您希望通过特定访问从JSON输出什么?这是一个包含映射的列表,请尝试像调用mydata[0][“1]”那样调用它。toString()