Reputation: 2690
I need to add an empty container at the top and the bottom of ListView so I can add automatically divider at the top and bottom. Here is my ListView builder class
ListView.separated(
itemCount: items.length + 2,
padding: EdgeInsets.only(top: 10),
itemBuilder: (context, index) {
print(index); //<= print 0 1 2
if (index == 0 || index > items.length) { //<= here is problem
return Container();
} else {
return itemBuilder(context, items[index]);
}
},
separatorBuilder: (BuildContext context, int index) =>
separator == null ? Container() : separator)
this should work however it gives me error when I try to compare index with 0
RangeError (index): Invalid value: Only valid value is 0: 1
Upvotes: 0
Views: 699
Reputation: 77
i tried ur code,and it works fine. maybe you should check if the items[] is empty
@override
Widget build(BuildContext context) {
var items = [1];
return ListView.separated(
itemCount: items.length + 2,
padding: EdgeInsets.only(top: 10),
itemBuilder: (context, index) {
print(index);
if (index == 0 || index > items.length) {
return Container(
height: 50,
color: Colors.pink,
);
} else {
return Container(
height: 50,
color: Colors.blue,
);
}
},
separatorBuilder: (BuildContext context, int index) => Container(
height: 50,
color: Colors.green,
),
);
Upvotes: 0
Reputation: 1060
update your code for else block
return itemBuilder(context, items[index-1]);
Upvotes: 1