【发布时间】:2021-04-24 15:22:28
【问题描述】:
尝试解析 json 响应,可以很好地处理字符串、int 类型值。 但是即使在放置 cast() 后将列表作为值时也会出错。 错误图片位于底部
class ChennaiModel{
final int ra;
final String ci;
final bool lo;
final List<String> ab;
ChennaiModel({
this.ra,this.ci,this.lo,this.ab
});
factory ChennaiModel.fromJson(Map<String,dynamic>parsedjson){
var streetsFromJson = parsedjson['streets'];
List<String> streetsList = streetsFromJson.cast<String>();
return new ChennaiModel(
ra:parsedjson['rank'],
ci:parsedjson['city'],
lo:parsedjson['love'],
ab:streetsList
);
}
}
Future<ChennaiModel> getchennai() async {
final response = await http.get(Uri.https('run.mocky.io','/v3/1496b5ef-873a-48db-9550-75195f2db3b4'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return ChennaiModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
【问题讨论】:
-
尝试列表
.from(streetsFromJson) -
您确定异常来自该行吗?该异常通常来自于尝试执行
String s = list.cast<String>();之类的操作。什么是堆栈跟踪? -
感谢提示,错误不在该行。我犯的错误是我在 Text() 小部件中传递了列表,它需要一个字符串所以后来我使用 listviewbuilder 遍历并显示它有没有其他方法可以在 build() 方法中遍历和构建??跨度>