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