如何在ListView.builder中访问含多属性的List类型模型数据?
解决Flutter ListView访问模型列表的下标错误
错误原因
你混淆了类和列表实例的概念:FirstSem是你的数据模型类,本身不是可索引的集合,所以不能用FirstSem[index]这种写法。真正存储课程数据的是你在model.dart里定义的subject列表,这才是需要通过下标访问的对象。
修正后的main.dart代码
将FirstSem[index]替换为subject[index],同时建议把itemCount改为subject.length(硬写固定值5不够灵活,列表数据变化时会出现显示异常):
ListView.builder( itemCount: subject.length, // 用列表长度替代固定数值 itemBuilder: (context, index) { return ListTile( title: Text(subject[index].title ?? ''), // 增加空值判断,避免null报错 trailing: Text(subject[index].code ?? ''), ); }, )
额外优化建议
为了让代码更健壮,可对FirstSem类做如下优化:
- 给属性添加
final保证不可变性,并用required强制构造参数非空(如果你的课程数据不会为null):
class FirstSem { final String title; final String code; FirstSem({required this.title, required this.code}); }
- 若课程数据不会动态变化,可将列表声明为
const:
const List<FirstSem> subject = [ FirstSem(title: "MatheMatics", code: "MTH162"), FirstSem(title: "Physics", code: "Phy162"), // 修正原拼写错误Physice FirstSem(title: "Digital Logic", code: "csc 162"), FirstSem(title: "C Programming", code: "csc 159"), FirstSem(title: "Introduction of Information Technology", code: "csc 160"), ];
内容的提问来源于stack exchange,提问作者Jeevan Shrestha
相关产品推荐
相关产品推荐

