What is ListView builder in flutter

A ListView is a widget that arranges a scrollable list of widgets linearly. Moreover, we can construct ListView using four ways. We’ll see each construction one by one. In today’s section, we’ll discuss ListView.builder constructor.

The ListView.builder constructor builds the children widget on demand based on the index of a list. And, to do that, the ListView.builder constructor takes an IndexedWidgetBuilder. In fact, the IndexedWidgetBuilder builds the children on demand.

When there are a large number of children widgets that we’re going to display on the screen, the ListView.builder constructor is ideal for that purpose.

You may wonder, how the builder is called when there are an infinite number of children widgets. In reality, builder is called only for those children that are actually visible.

When we use ListView.builder constructor, we’ll always provide a non-null item count.

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 builder constructor and display each student’s name and image.

ListView.builder(
        padding: const EdgeInsets.all(10.0),
        itemCount: students.length,
        itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
...
/// the code is incomplete for brevity
/// you'll find the full code below

The ListView builder constructor has many properties, yet we’ve used only three of them. Since we have several children widgets, so we can use padding property to make them separated.

However, here most important properties are itemCount and itemBulder.

We’ve counted the length of the students objects by this line:

itemCount: students.length,

Actually, we’ve already created three student objects, therefore, there are three students, so to say. To clarify, we’ve provided a non-null value to the itemCount parameter of the ListView builder constructor. It helps ListView to measure how much it has to scroll.

Another very important parameter is itemBuilder callback. Until the indices become less than the itemCount, the itemBuilder is called.

itemBuilder: (ctx, i) => ChangeNotifierProvider.value(...)

As the name suggests, the item builder builds the items. Subsequently, it cannot return null widgets.

We’re going to see the full code soon. But before that let’s run the app and see the first screenshot.

ListView Builder sample one
ListView Builder sample one

The ListView builder constructor displays the first student object belonging to our list. However, if we want to child reordering, this constructor doesn’t support that.

To do that either we have to use ListView or ListView.custom.

What is the difference between ListView and ListView builder in flutter?

The biggest difference between ListView and ListView builder is in the process of building children widgets.

The ListView builder constructor builds children widgets on demand. The ListView widget cannot do that.

With the help of ListView builder constructor we should not return a previously constructed widget. That sounds quite natural. Because it will build children on demand.

If we have already constructed widgets, then use ListView. That is also another big difference between them.

Let’s show the full code now.

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

class ListViewBuilderSample extends StatelessWidget {
  const ListViewBuilderSample({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.builder(
        padding: const EdgeInsets.all(10.0),
        itemCount: students.length,
        itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
          value: students[i],
          child: Center(
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.all(5),
                  child: Text(
                    students[i].name,
                    style: const TextStyle(
                      fontFamily: 'Allison',
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Image.network(
                  students[i].imageUrl,
                  fit: BoxFit.cover,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Is ListView builder scrollable?

Certainly, ListView builder constructor is scrollable. Now, we can scroll and see the other student instances.

Let’s see the second student instance.

ListView Builder sample two
ListView Builder sample two

And after that, we can also scroll again and see the third student instance.

ListView Builder sample three
ListView Builder sample three

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 Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

6 responses to “What is ListView builder in flutter”

  1. […] are similarities in ListView.builder and ListView.separated constructors, as they both take at least one IndexedWidgetBuilder. That […]

  2. […] ListView using 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. […] are similarities in ListView.builder and ListView.separated constructors, as they both take at least one IndexedWidgetBuilder. That […]

  4. […] if the number of child items are too large, consider using ListView constructors like ListView.builder, ListView.custom, and ListView.separated. These widgets create items visible on demand. […]

  5. […] that, the builder property of the Future Builder widget will return a ListView builder constructor which will display the post as the List […]

  6. […] have used a ListView builder constructor. Inside a container widget we check this with a simple […]

Leave a Reply