Named and Required Parameters
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 13 of 33.
With three or four fields, Book('Dune', 'Frank Herbert', 412) is hard to read, and swapping two strings by mistake is easy. Named parameters put the field's name at every call:
class Book {
final String title;
final int pages;
Book({required this.title, required this.pages});
}
Book(title: 'Dune', pages: 412)The curly braces in the constructor make the parameters named. You write each one as name: value, in any order.
The widgets you have used take named parameters too, such as Text(style: ...) or ListTile(title: ...).
required means the parameter must be given: leave out pages: and the editor shows an error before the app runs.
Challenge
MediumShow how long each book is:
- add a
final int pages;field toBook - change the constructor to named, required parameters, and write the books as
Book(title: 'Dune', author: 'Frank Herbert', pages: 412). Emma has474pages and Ulysses730 - show
412 pagesat the end of each row, as the tile'strailing:
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'),
];
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),
subtitle: Text(book.author),
),
],
),
),
);
}
}
class Book {
final String title;
final String author;
Book(this.title, this.author);
}
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