Menu
CoddyTech

Building Rows With a Builder

Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 6 of 33.

A playlist can hold thousands of songs. Writing a ListTile for each one is not possible, and building them all at once would be slow. ListView.builder builds each row only when it scrolls into view.

ListView.builder(
  itemCount: songs.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(songs[index]));
  },
)

itemCount says how many rows there are. itemBuilder is a function the list calls for each row, with the row's index: 0 for the first row, 1 for the next, and so on. It returns the widget for that row.

Use songs.length for itemCount, so the list grows when the list of songs does. A number bigger than the list asks for a song that is not there, and the app stops with a RangeError.

challenge icon

Challenge

Easy

The playlist has 15 songs, but only 3 show. Fix itemCount so every song is in the list, down to Starfall, and stays right when songs are added.

Try it yourself

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> songs = [
      'Morning Light',
      'Paper Planes',
      'City Rain',
      'Slow River',
      'Neon Nights',
      'Golden Hour',
      'Northern Wind',
      'Blue Harbor',
      'Quiet Storm',
      'Summer Static',
      'Echo Valley',
      'Last Train',
      'Silver Lines',
      'Open Road',
      'Starfall',
    ];
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Playlist')),
        body: ListView.builder(
          itemCount: 3,
          itemBuilder: (context, index) {
            return ListTile(title: Text(songs[index]));
          },
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lists and Screens

Practice on your own: Online Flutter compiler