Menu
CoddyTech

Fields That Can Be Empty

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

Not every contact has an email. A field that may hold nothing has a ? after its type, and its value is null when nothing was given:

class Contact {
  final String name;
  final String? email;

  Contact({required this.name, this.email});
}

Without required, email: may be left out: Contact(name: 'Alan Turing') has an email of null.

You cannot call a method on null, so Dart stops you from writing contact.email.toLowerCase(). Write ?. instead of the dot: contact.email?.toLowerCase() calls the method when there is an email, and gives null when there is not. Then ?? picks a fallback:

Text(contact.email?.toLowerCase() ?? 'No email')
challenge icon

Challenge

Easy

Emails were typed with random capitals, and Alan has none. Give each tile a subtitle: that shows the email in small letters, or No email when there is none.

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<Contact> contacts = [
      Contact(name: 'Ada Lovelace', email: 'Ada@Example.com'),
      Contact(name: 'Alan Turing'),
      Contact(name: 'Grace Hopper', email: 'GRACE@NAVY.MIL'),
    ];
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Contacts')),
        body: ListView(
          children: [
            for (Contact contact in contacts)
              ListTile(
                title: Text(contact.name),
              ),
          ],
        ),
      ),
    );
  }
}

class Contact {
  final String name;
  final String? email;

  Contact({required this.name, this.email});
}
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