비어 있을 수 있는 필드
Coddy Flutter 여정의 목록과 화면 섹션에 포함된 레슨. 33개 중 14번째.
모든 연락처에 이메일이 있는 것은 아닙니다. 값이 없을 수도 있는 필드는 타입 뒤에 ?가 붙으며, 값이 주어지지 않았을 때는 null이 됩니다:
class Contact {
final String name;
final String? email;
Contact({required this.name, this.email});
}required가 없으면 email:을 생략할 수 있습니다. Contact(name: 'Alan Turing')의 email은 null입니다.
null에는 메서드를 호출할 수 없으므로, Dart는 contact.email.toLowerCase()를 작성하지 못하게 합니다. 점 대신 ?.를 작성하세요. contact.email?.toLowerCase()는 이메일이 있으면 메서드를 호출하고, 없으면 null을 반환합니다. 그런 다음 ??로 대체값을 지정합니다:
Text(contact.email?.toLowerCase() ?? 'No email')챌린지
쉬움이메일에는 무작위로 대문자가 섞여 있고, Alan에게는 이메일이 없습니다. 각 타일에 이메일을 소문자로 표시하는 subtitle:을 넣고, 이메일이 없으면 No email을 표시하세요.
직접 해보기
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});
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
목록과 화면의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러