What is ListView separated

There are similarities in ListView.builder and ListView.separated constructors, as they both take at least one IndexedWidgetBuilder. That is itemBulder parameter, which builds the children on demand.

However, there is one difference between these two ListView constructors.

The ListView.separated constructor has another parameter separatorBuilder, which similarly builds separator children which appear in between the child items.

As a whole, the ListView.separated constructor is a very useful API. We can use it to add separators between child items inside a flutter ListView.

Firstly, let us take a look at the screenshots. Secondly, after that, we’ll discuss the code snippets. You may compare ListView.separated with the previous article on ListView.builder constructor. That’ll clarify if any doubt arises.

The separators have a special character. They only appear between list items. That means, the last separator appears before the last item.

ListView separated sample one
ListView separated sample one

The first screenshot clearly displays the separator after the first student instance. The separator, a horizontal grey line, is attached with the image, as we’ve not kept the divider inside any container with a well-defined padding parameter.

Now, we’ll take a look at the second screenshot that shows no separator after the last student instance.

ListView separated sample two
ListView separated sample two

Therefore, we have come to know one key point about the ListView.separated constructor. There will be no separator above the first item, and below the last item.

As we scroll, we find this characteristic quite logical. After the last instance we don’t really need any separator.

It’s also true for the first one. Why? Because it doesn’t look good if one unnecessary separator shows up above the first instance.

Although we’ve only used a Divider widget as the separatorBuilder here, but we could have used a list of other widgets as its separator children in between the student instances.

For a fixed number of children, the ListView separated constructor is very useful.

How do you add a separator to a ListView in flutter?

Now it’s time to add a separator to a ListView in flutter. And, it’s a high time to show the code snippets.

We’ve already seen the screenshots that show the separators in between the student items.

To understand this mechanism, let’s consider a model class of students that will have id, name and an image property.


  
import 'package:flutter/foundation.dart';

class Student with ChangeNotifier {
  final String id;
  final String name;
  final String imageUrl;

  Student({
    required this.id,
    required this.name,
    required this.imageUrl,
  });
}

class Students with ChangeNotifier {
  /// adding id and images
  List<Student> students = [
    Student(
      id: 's1',
      name: 'Json',
      imageUrl:
          'https://cdn.pixabay.com/photo/2018/09/11/19/49/education-3670453_960_720.jpg',
    ),
    Student(
      id: 's2',
      name: 'Limpi',
      imageUrl:
          'https://cdn.pixabay.com/photo/2016/11/29/13/56/asian-1870022_960_720.jpg',
    ),
    Student(
      id: 's3',
      name: 'Maria',
      imageUrl:
          'https://cdn.pixabay.com/photo/2017/09/21/13/32/girl-2771936_960_720.jpg',
    ),
  ];
}

By the way, we use provider package to provide the data model objects.

As we can see in the above code, there are three student objects that we’ve already created.

Next, we’ll see the rest part of the code, where we will use a ListView.separated constructor and display each student’s name and image, along with the separators.

import 'package:flutter/material.dart';
import 'package:flutter_artisan/models/student.dart';
import 'package:provider/provider.dart';

class ListViewSeperatedSample extends StatelessWidget {
  const ListViewSeperatedSample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Students Name',
      home: StudentsHomePage(),
    );
  }
}

class StudentsHomePage extends StatelessWidget {
  const StudentsHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final students = Provider.of<Students>(context).students;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Students Home Page'),
      ),
      body: ListView.separated(
        padding: const EdgeInsets.all(10.0),

        /// required
        itemCount: students.length,

        /// required
        itemBuilder: (context, index) => ChangeNotifierProvider.value(
          value: students[index],
          child: Center(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.all(5),
                  child: Text(
                    students[index].name,
                    style: const TextStyle(
                      fontFamily: 'Allison',
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(5),
                  child: Text(
                    'Student ID: ${students[index].id}',
                    style: const TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Image.network(
                  students[index].imageUrl,
                  fit: BoxFit.cover,
                ),
              ],
            ),
          ),
        ),

        /// required
        separatorBuilder: (BuildContext context, int index) =>
            ChangeNotifierProvider.value(
          value: students[index],
          child: const Center(
            child: Divider(
              height: 10,
              thickness: 10,
              color: Colors.black38,
            ),
          ),
        ),
      ),
    );
  }
}

The above code snippet clearly shows us how we can create fixed-length scrollable linear array of list – student instances, which again are separated by list item separators.

Three parameters are required when we use ListView separated constructor. They are itemCount, itemBuilder, and separatorBuilder.

Between these three required parameters, itemBuilder, and separatorBuilder are callbacks; however, they serve different purposes.

The itemBuilder callback works at tandem with itemCount parameter.

Consequently, the item builder callback will only be called with the indices greater than, or equal to zero. Whatsoever, it always should be less than the item count parameter.

The same way, separator builder callback will only be called with the indices greater than, or equal to zero. Whatsoever, it always should be less than itemCount – 1.

That’s why, we don’t see any separator above the first item, and below the last item.

In addition to these properties, the item builder and separator builder callbacks should always return a non-null widget and always create widgets when called.

By the way, you may want to take a look at the other Scrolling Widgets, before we close down further reading on this topic.

We have a list below.

What is ListView Flutter? How do I use ListView in Flutter?

How do I use SingleChildScrollView in flutter?

What is GridView and how do you centre a GridView item in Flutter?

What is GridView builder in Flutter?

What is the grid view in Flutter?

What is GridView count in flutter?

What is GridView.extent in Flutter?

How do I make my collapsing toolbar flutter?

What is SliverGrid in flutter?

How to use CustomScrollView in Flutter?

How to use NestedScrollView in flutter?

How to use PageView in Flutter

What is PageView builder in flutter?

What is PageView custom in flutter?

How to use DraggableScrollableSheet

What is ListView builder in flutter

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

4 responses to “What is ListView separated”

  1. […] We can construct ListView using four methods. We’ve already seen how we can use ListView by constructors like ListView.builder, ListView.custom, and ListView.separated. […]

  2. […] four ways. We’ve seen two ListView constructors in our previous sections. ListView.builder and ListView.separated constructors play different roles in building a scrollable, linear array of […]

  3. […] using ListView constructors like ListView.builder, ListView.custom, and ListView.separated. These widgets create items visible on demand. That definitely saves system […]

Leave a Reply