delmin
delmin

Reputation: 2690

Add empty container at the top and the bottom of a ListView

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

Answers (2)

mickey
mickey

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,
      ),
    );

enter image description here

Upvotes: 0

R7G
R7G

Reputation: 1060

update your code for else block

return itemBuilder(context, items[index-1]);

Upvotes: 1

Related Questions