Search code examples
listviewflutterdivider

flutter listView.Builder hide the divider on last list item


How can one hide divider in the last item when creating list with ListView.Builder?

It's fairly easy to add divider for each item, but what is the logic to dismiss divider on the last item in the list?

There is no concrete stackoverflow question with a concrete example of implementing this task.

   Widget build(BuildContext context) {
return 
    ListView.builder(
      shrinkWrap: true,
      physics: ScrollPhysics(),
      itemCount: OffersList.length,
      itemBuilder: (context, index) {
        Offer item = OffersList[index];
        return ListItem(context, item);
      },
    );
  }



Widget ListItem(BuildContext context, Offer item) {
if ( index == OffersList.length - 1) {
  dividerChecker = EmptyContainer();
} else {
  dividerChecker = Divider();
}
return Column(
  children: <Widget>[
    OfferListItem(
      offerData: item,
      status: status,
      userType: userType,
    ),
    dividerChecker,
  ],
);

}

Solution as suggested:

using ListView.separator instead of ListView.Builder:

        ListView.separated(
      separatorBuilder: (BuildContext context, int index) => new Divider(),
      shrinkWrap: true,
      physics: ScrollPhysics(),
      itemCount: OffersList.length,
      itemBuilder: (context, index) {
        Offer item = OffersList[index];
        return offerListItem(context, item);
      },
    ),
Widget offerListItem(BuildContext context, Offer item) {
return Column(
  children: <Widget>[
    OfferListItem(
      offerData: item,
      status: status,
      userType: userType,
    ),
  ],
);

}


Solution

  • You can use ListView.separated() for a dynamicly created list or ListTile.divideTiles for a short static list. Neither of these methods add a divider after the last list item.

    ListTile.divideTiles

    enter image description here

    ListView(
      children: ListTile.divideTiles( //          <-- ListTile.divideTiles
          context: context,
          tiles: [
            ListTile(
              title: Text('Horse'),
            ),
            ListTile(
              title: Text('Cow'),
            ),
            ListTile(
              title: Text('Camel'),
            ),
            ListTile(
              title: Text('Sheep'),
            ),
            ListTile(
              title: Text('Goat'),
            ),
          ]
      ).toList(),
    )
    

    ListView.separated

    enter image description here

    ListView.separated(
      itemCount: 100,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text('$index sheep'),
        );
      },
      separatorBuilder: (context, index) {
        return Divider();
      },
    )
    

    This returns two widgets for every item, except for the last item. The separatorBuilder is used to add the divider.

    If you do want a divider after the last item see my fuller answer.