Menu
CoddyTech

Widgets From Data With map

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

A list's map makes a new list by running a function on every item. It is how you turn a list of data into a list of widgets:

ListView(
  children: books.map((book) => ListTile(title: Text(book.title))).toList(),
)

(book) => ListTile(...) is a short function: it takes one book and gives back the tile after the arrow. map calls it for each book, in order.

map does not give back a List yet, so end with .toList(): children: needs a list. A collection for does the same job. Use the one you find easier to read; you will see both in real apps.

map also turns data into other data: books.map((book) => book.title).toList() is a List<String> of the titles.

challenge icon

Challenge

Easy

The list has five books, but the screen shows three tiles written by hand. Replace the three tiles with books.map(...).toList(), so every book gets a tile with its title and its author as the subtitle.

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<Book> books = [
      Book('Dune', 'Frank Herbert'),
      Book('Emma', 'Jane Austen'),
      Book('Ulysses', 'James Joyce'),
      Book('Coraline', 'Neil Gaiman'),
      Book('Beloved', 'Toni Morrison'),
    ];
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Books')),
        body: ListView(
          children: [
            ListTile(
              title: Text(books[0].title),
              subtitle: Text(books[0].author),
            ),
            ListTile(
              title: Text(books[1].title),
              subtitle: Text(books[1].author),
            ),
            ListTile(
              title: Text(books[2].title),
              subtitle: Text(books[2].author),
            ),
          ],
        ),
      ),
    );
  }
}

class Book {
  final String title;
  final String author;

  Book(this.title, this.author);
}
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