3 Ways to Add Separators between Items in a ListView

Last updated on April 28, 2021 Guest Contributor Loading... Post a comment

The following examples show you a couple of different ways to insert separators between items in a list view.

Example 1: Using ListView.separated

In Flutter, you can use ListView.separated to easily create a list view whose items are separated by separators (or dividers). A separator only appears between two list items and never stands before the first or sits after the last item.

Simple use:

final _myList = [
    // Your list data here
];

/* .. */

ListView.separated(
      itemCount: _myList.length,
      itemBuilder: (context, index){
             return /* Your list item widget here */;
      }, 
      separatorBuilder: (context, index){ 
             return /* Your separator widget here */;
      }
),

This example uses the Divider widget to create separators.

Preview:

The full code with explanations:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(primaryColor: Colors.blue),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  // A list of fiction products
  final List<String> _myList = List.generate(100, (index) => 'Product $index');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: ListView.separated(
            itemCount: _myList.length,
            // The list items
            itemBuilder: (context, index) {
              return Text(
                _myList[index],
                style: TextStyle(fontSize: 24),
              );
            },
            // The separators
            separatorBuilder: (context, index) {
              return Divider(
                color: Theme.of(context).primaryColor,
              );
            }),
      ),
    );
  }
}

Example 2: Adding a top-border to every item widget except the first one

In this example, we will create separators by giving all items except the first a top border.

Note: If you just give all the items in the list a bottom border, then the last item will have one. This may be an undesirable result in many situations.

Preview:

The code:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(primaryColor: Colors.green),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  // List data
  final List<String> _myList = List.generate(100, (index) => 'Item $index');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: ListView.builder(
          itemCount: _myList.length,
          // The list items
          itemBuilder: (context, index) {
            return Container(
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                border: index == 0
                    ? Border() // This will create no border for the first item
                    : Border(
                        top: BorderSide(
                            width: 1,
                            color: Theme.of(context)
                                .primaryColor)), // This will create top borders for the rest
              ),
              child: Text(
                _myList[index],
                style: TextStyle(fontSize: 24),
              ),
            );
          },
        ),
      ),
    );
  }
}

Example 3: Using Card widget

The two examples above make the separators are horizontal lines. In this example, we will create separators that are wide ranges with a color that is different from the background color of each list item.

Preview:

The code:

// main.dart
import 'package:flutter/material.dart';
import 'dart:math';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(primaryColor: Colors.blue),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  // Dummy list data
  final List<Map<String, dynamic>> _people = List.generate(100,
      (index) => {'name': 'Person \#$index', 'age': Random().nextInt(100) + 1});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: ListView.builder(
          itemCount: _people.length,
          // The list items
          itemBuilder: (context, index) {
            return Card(
              margin: EdgeInsets.symmetric(vertical: 5),
              color: Colors.amberAccent,
              child: ListTile(
                title: Text(
                  _people[index]['name'],
                  style: TextStyle(fontSize: 24),
                ),
                trailing: Text(
                  _people[index]['age'].toString(),
                  style: TextStyle(fontSize: 24),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

Conclusion

We’ve gone through a few techniques of implementing a list view whose items that separated by separators. These are useful and sooner or later you will find some scenarios where you need one of them. If you would like to explore more about Flutter and Dart, take a look at the following articles:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x