Reputation: 1247
What I want to do is to add an extra LisTile
to the last of ListView
but I still don't figure it out.
My current code is like this.
child: ListView.builder(
itemBuilder: (context, index) {
if (index == 0) {
// Add an extra item to the start
return ListTile(
...
);
}
index -= 1;
final item = _items[index];
// I want to an extra item here as well
if (index == _items.length) {
return ListTile();
}
return ListTile(
...
);
},
itemCount: _items.length + 2,
I've already tried the way above, but it doesn't work. There is an error.
Invalid value: not in range 0..4, inclusive 5
When I changed itemCount
to _items.length + 1
, it doesn't show the extra ListTile
I want to add to the end.
Upvotes: 2
Views: 2013
Reputation: 119
If you want to add to the beginning and the end as well check below
child: ListView.builder(
itemBuilder: (context, index) {
if (index == 0) {
// Add an extra item to the start
return ListTile(
...
);
}
if (index == _items.length + 1) {
return ListTile();
}
index -= 1;
final item = _items[index];
return ListTile(
...
);
},
itemCount: _items.length + 2,
Upvotes: 3
Reputation: 119
your bug is here:
itemCount: _items.length + 2,
you should increase it by one
because you added 2 elements and for the last call you get index = list.length + 1, and then you subtract 1 from it, and you end up 1 over your length.
ex lets say your list have 5 elements, because you have
itemCount: _items.length + 2
Listview will call your func 7 times, and in 7th call your index is 6 and you are doing index =-1, which equals to 5, and 5 is over your range. (you have form 0 to 4)
Upvotes: 0