Flutter app development tutorials by Andrea Bizzotto

Adding top and bottom separators with ListView.separated

ListView.separated is a handy API that we can use to add separators between items inside a Flutter ListView.

According to the documentation:

Separators only appear between list items: separator 0 appears after item 0 and the last separator appears before the last item.

This means that there are no separators above the first item, and below the last item.

This is visually noticeable on iOS, where lists can over-scroll by default.

Here's some code to set things straight, and add top and bottom separators to your ListViews:

class ListViewWithAllSeparators<T> extends StatelessWidget { const ListViewWithAllSeparators({Key key, this.items, this.itemBuilder}) : super(key: key); final List<T> items; final Widget Function(BuildContext context, T item) itemBuilder; @override Widget build(BuildContext context) { return ListView.separated( itemCount: items.length + 2, separatorBuilder: (_, __) => Divider(height: 0.5), itemBuilder: (context, index) { if (index == 0 || index == items.length + 1) { return Container(); // zero height: not visible } return itemBuilder(context, items[index - 1]); }, ); } }

You're welcome. 😉

Want more?

Support my work and fast-track your Flutter learning with my in-depth courses.