0
0
Fluttermobile~5 mins

ListView.builder in Flutter

Choose your learning style9 modes available
Introduction

ListView.builder helps you show a long list of items on the screen efficiently. It creates only the items you see, saving memory and making your app faster.

When you want to show a long list of messages in a chat app.
When displaying a list of contacts or friends.
When showing a list of products in a shopping app.
When you want to load items as the user scrolls down.
When the list size is unknown or very large.
Syntax
Flutter
ListView.builder(
  itemCount: numberOfItems,
  itemBuilder: (BuildContext context, int index) {
    return WidgetForItem(index);
  },
)

itemCount tells how many items to build.

itemBuilder is a function that creates each item widget using the current index.

Examples
Shows 5 text items labeled Item 0 to Item 4.
Flutter
ListView.builder(
  itemCount: 5,
  itemBuilder: (context, index) {
    return Text('Item $index');
  },
)
Shows nothing because itemCount is zero.
Flutter
ListView.builder(
  itemCount: 0,
  itemBuilder: (context, index) {
    return Text('No items');
  },
)
Builds a list of tiles from a list of strings called items.
Flutter
ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(items[index]),
    );
  },
)
Sample App

This app shows a scrollable list of fruits. Each fruit has a circle with its first letter and its name next to it.

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final List<String> fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Fruit List')),
        body: ListView.builder(
          itemCount: fruits.length,
          itemBuilder: (context, index) {
            return ListTile(
              leading: CircleAvatar(child: Text(fruits[index][0])),
              title: Text(fruits[index]),
            );
          },
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

ListView.builder only builds visible items, so it uses less memory than ListView with all children.

Time complexity is O(n) for n visible items, not all items.

Common mistake: forgetting to set itemCount, which can cause infinite list or errors.

Use ListView.builder when you have many items or dynamic lists. Use ListView(children: [...]) for small fixed lists.

Summary

ListView.builder creates list items on demand for better performance.

Use itemCount to tell how many items to build.

itemBuilder builds each item widget using the index.