Menu
CoddyTech

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 icon

Challenge

Medium

Show how long each book is:

  • add a final int pages; field to Book
  • change the constructor to named, required parameters, and write the books as Book(title: 'Dune', author: 'Frank Herbert', pages: 412). Emma has 474 pages and Ulysses 730
  • show 412 pages at the end of each row, as the tile's trailing:

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);
}
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