Flutter从列表读取数据报错:String无法赋值给int,求原因与解决方法
嘿,我来帮你搞定这个Flutter的小问题!
错误原因分析
你的values是一个List(列表),而不是Map(键值对字典)。列表的索引只能是整数(比如用values[0]获取第一个元素),但你直接写了values['category']——这里的'category'是字符串,而列表期望你传入整数类型的索引,类型不匹配自然就报错啦,也就是你看到的「the argument type 'String' can't be assigned to the parameter type 'int'」。
快速修复方法
你需要先从列表里取出对应的Map元素,再访问它的category键,分两种场景:
场景1:访问单个元素(比如取列表第一个元素)
如果只是想展示列表里某一个元素的category,直接用整数索引定位元素再取值:
Text("${values[0]['category']}"), Card( color: Colors.white, child: Text( "عروض ", style: TextStyle(color: Colors.red, fontSize: 20, fontWeight: FontWeight.w900) ) ),
场景2:遍历整个列表(常用的列表展示场景)
如果要把列表里所有元素都展示出来,推荐用ListView.builder来遍历,这样性能更好(尤其是列表数据多的时候):
ListView.builder( itemCount: values.length, // 列表总长度 itemBuilder: (context, index) { // 每次遍历拿到当前索引对应的Map元素 final currentItem = values[index]; return Card( color: Colors.white, child: Column( children: [ Text("${currentItem['category']}"), Text( "عروض ", style: TextStyle(color: Colors.red, fontSize: 20, fontWeight: FontWeight.w900) ), ], ), ); }, )
更规范的进阶实现方式(推荐)
直接用Map虽然能快速实现,但时间久了容易出现拼写错误,而且没有类型提示。推荐把Map转换成自定义的Dart类,让代码更健壮、易维护:
第一步:创建Category实体类
class Category { final String name; final String backImage; final String iconImage; // 构造方法 Category({ required this.name, required this.backImage, required this.iconImage, }); // 从Map转换为Category对象的工厂方法 factory Category.fromMap(Map<String, dynamic> map) { return Category( name: map['category'], backImage: map['categorybackimage'], iconImage: map['categoryimage'], ); } }
第二步:把原始列表转换成Category对象列表
// 把原来的List<Map>转成List<Category> List<Category> categoryList = values.map((item) => Category.fromMap(item)).toList();
第三步:使用的时候更直观
ListView.builder( itemCount: categoryList.length, itemBuilder: (context, index) { final category = categoryList[index]; return Card( color: Colors.white, child: Column( children: [ // 直接通过类的属性访问,IDE会有提示,不会写错 Text(category.name), Text( "عروض ", style: TextStyle(color: Colors.red, fontSize: 20, fontWeight: FontWeight.w900) ), ], ), ); }, )
这样做的好处是:如果不小心把category拼写成cateogry,IDE会立刻报错提醒你,避免了 runtime 才发现的错误,代码可读性也更高。
内容的提问来源于stack exchange,提问作者Abdelrahman M. Elmarakby
相关产品推荐
相关产品推荐

