我正在构建一个静态ListView。如何解决此错误?此外,我如何将UI添加到ListView
以下是我的类MatchData代码:
class MatchData {
String date, team1, team2, time;
MatchData({@required this.date, @required this.team1, @required this.team2, @required this.time});
}
以下是我想在ListView中显示的数据:
final List<MatchData> dayMatch = [
MatchData(
date: '12/02/2020',
team1: 'Mumbai Indians',
team2: 'Bangalore',
time: '16:00'),
MatchData(
date: '12/02/2020',
team1: 'Mumbai Indians',
team2: 'Bangalore',
time: '16:00')
];
match() {
return dayMatch;
}
以下是我的小工具的主体:
body: Center(child: ListView.builder(itemBuilder: (context, index) {
return Card(
child: Row(
children: <Widget>[
Text(dayMatch[index].date),
Text(dayMatch[index].team1),
Text(dayMatch[index].time),
Text(dayMatch[index].team2),
],
),
);
}
如果不指定itemCount
,并且屏幕足够大,可以显示十个项目,则ListView.builder()
会生成十多个子项,如果向下滚动,则会生成更多子项。
在您的情况下,ListView.builder()
尝试构建两个以上的子项,而您的列表(dayMatch(只有两个元素,这就是出现错误的原因。
要解决此问题,只需将项数传递给itemCount
参数,或者如果项数固定且较小,则使用ListView的默认构造函数会更好。ListView.builder()
为了灵活,在后台做了更多的计算,这对于一个小列表来说有点太多了。
您可以使用"itemCount"。
child: ListView.builder(
itemCount: dayMatch.length,
itemBuilder: (context, index) {
return Card(
child: Row(
children: <Widget>[
Text(dayMatch[index].date),
Text(dayMatch[index].team1),
Text(dayMatch[index].time),
Text(dayMatch[index].team2),
],
),
);
},
),