Flutter listview spacing

Flutter ListView Spacing

When working with ListView in Flutter, spacing between items can be controlled using the ListView.builder constructor along with some additional properties. Below is an example of how you can achieve spacing in a ListView:


ListView.builder(
  itemCount: 10,
  itemBuilder: (context, index) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0),
      child: ListTile(
        title: Text('Item $index'),
        subtitle: Text('Subtitle $index'),
      ),
    );
  },
)
  

In the above example, the ListView.builder creates a ListView with 10 items. The itemBuilder is a callback that builds each item in the ListView. By wrapping the ListTile widget with Padding, we add vertical spacing of 8.0 units between each item.

Alternate Method:

Another approach to add spacing in ListView is by using the ListView.separated constructor. This constructor allows you to specify both an item builder and a separator builder:


ListView.separated(
  itemCount: 10,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text('Item $index'),
      subtitle: Text('Subtitle $index'),
    );
  },
  separatorBuilder: (context, index) {
    return SizedBox(height: 8.0);
  },
)
  

In the above example, the ListView.separated creates a ListView with 10 items. The itemBuilder builds each item as before, while the separatorBuilder adds a separator of height 8.0 units between items.

These are two common approaches to control the spacing between items in a ListView in Flutter. Choose the one that best fits your use case.

Leave a comment