Flutter对接MySQL报错:type 'string' is not a subtype of type 'int' of 'index'
问题根源
你在FutureBuilder传递数据给ItemList时,错误地将本身已是List类型的snapshot.data用方括号包裹,形成了嵌套List。
原错误代码:
ItemList( list: [snapshot.data], )
这会让ItemList接收的list变成类似[[{item_name: ...}, {item_name: ...}]]的结构。当你在ListView.builder中执行list[i]['item_name']时,list[i]取到的是内部的List对象,而List只能用int类型索引,你用字符串'item_name'索引自然会触发type 'string' is not a subtype of type 'int' of 'index'错误。
修复方案
直接传递snapshot.data给ItemList,去掉多余的方括号:
return snapshot.hasData ? ItemList( list: snapshot.data!, // hasData为true时snapshot.data非空,用!断言 ) : const Center( child: CircularProgressIndicator(), );
额外优化建议
- 删除
ItemList中不必要的空判断:因为构造函数要求list必填,且只有snapshot.hasData为true时才会创建ItemList,list不可能为null,直接用itemCount: list.length即可。 - 给
getData方法添加更精确的泛型声明,提升代码类型安全性:
Future<List<Map<String, dynamic>>> getData() async { final response = await http.get(Uri.parse(url)); return List<Map<String, dynamic>>.from(json.decode(response.body)); }
内容的提问来源于stack exchange,提问作者Raven Derana
相关产品推荐
相关产品推荐

