A Class for Your Data
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 12 of 33.
A book is more than one string: it has a title and an author, and they belong together. A class describes a new kind of value made of named parts, called fields:
class Book {
final String title;
final String author;
Book(this.title, this.author);
}The line Book(this.title, this.author); is the constructor: it makes a new book and fills in its fields, in that order. Book('Dune', 'Frank Herbert') is a book with the title Dune.
Read a field with a dot: book.title, book.author. A list of books has the type List<Book>, the same way a list of strings is List<String>.
A class goes on its own, outside your widget classes, usually at the bottom of the file.
Challenge
MediumThe Book class has only a title. Give it an author:
- add a
final String author;field and fill it in the constructor, after the title - give each book its author:
Frank Herbert,Jane AustenandJames Joyce - show the author as each tile's
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'),
Book('Emma'),
Book('Ulysses'),
];
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Text('Books')),
body: ListView(
children: [
for (Book book in books)
ListTile(
title: Text(book.title),
),
],
),
),
);
}
}
class Book {
final String title;
Book(this.title);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows4Your Own Classes
A Class for Your DataNamed and Required ParametersFields That Can Be EmptyWidgets From Data With mapFilter a List With whereLook Up in a Map6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler