How to Create ListView with Separator in Flutter

ListView makes its children scroll. Most of the time, we require a separator to distinguish between every child of ListView. This separator is basically a divider, which can be a line.

In the previous blog post, I wrote about how to use ListViews basically in Flutter. Now, let’s go through how to create a ListView with the divider in Flutter.

To create a divider with each of ListView child, you should use ListView.separated constructor. It accepts itemBuilder as well as separatorBuilder. The separator can be built using Divider class. The Divider is basically used to draw thin horizontal lines.

See the snippet below:

ListView.separated(
  itemCount: data.length,
  separatorBuilder: (BuildContext context, int index) => Divider( height: 3, color: Colors.white),
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 150,
      color: Colors.red,
      child: Center(child: Text('${data[index]}')),
    );
  }
)

Following is the full example of Listview with separators in Flutter.

import 'package:flutter/material.dart';


class SeparatorExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: MainScreen()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class MainScreen extends StatelessWidget {
  final data= ["one","two","three","four","five","six","seven","eight","nine","ten"];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ListView with Separator Example'),
      ),
      body: Center(
        child: ListView.separated(
  itemCount: data.length,
  separatorBuilder: (BuildContext context, int index) => Divider( height: 3, color: Colors.white),
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 150,
      color: Colors.red,
      child: Center(child: Text('${data[index]}')),
    );
  }
)
      ),
    );
  }
}

And here’s the output:

flutter listview separator example

I hope this Flutter tutorial helped you! Thank you for reading!

Leave a Comment

Your email address will not be published. Required fields are marked *