回顾:安全处理空值
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 82 课,共 94 课。
挑战
简单你正在为移动应用构建用户资料系统。创建一个 UserProfile 类,展示你对 Dart 空安全功能的理解。
实现一个 UserProfile 类,包含以下内容:
- 不可空属性(必须始终有值):
- 类型为
int的id - 类型为
String的createdDate
- 类型为
- 可空属性(初始化时可以为 null):
- 类型为
String?的name - 类型为
String?的email - 类型为
int?的age
- 类型为
- 延迟初始化属性:
- 类型为
String的displayName,使用late关键字声明
- 类型为
- 构造函数:
- 将
id和createdDate作为必需参数 - 将
displayName初始化为"Guest"
- 将
方法:
void printProfile()按以下格式打印用户资料:User Profile: ID: <id> Created: <createdDate> Name: <name or 'Not provided'> Email: <email or 'Not provided'> Age: <age or 'Not provided'> Display Name: <displayName> -------------------- 方法:
void updateEmail(String? newEmail)- 使用新值更新
email属性。
- 使用新值更新
- 方法:
String getDisplayName()- 如果
name不为 null,则设置displayName = name!(使用空断言运算符) - 返回
displayName的当前值
- 如果
重要:更新 name 属性后,你必须调用 getDisplayName() 来更新 displayName 字段,然后才能再次打印资料。
完成代码,创建并更新资料,然后按预期输出所示显示信息。
亲手试试
void main() {
// 创建用户资料
final profile = UserProfile(1, 'today');
// 打印初始用户资料
profile.printProfile();
// 更新用户资料
profile.name = 'John Doe';
profile.updateEmail('john@example.com');
profile.age = 30;
// 更新显示名称并打印更新后的用户资料
profile.getDisplayName(); // 调用此方法来更新 displayName
profile.printProfile();
}
class UserProfile {
// TODO: 添加属性(id、createdDate、name、email、age、displayName)
// TODO: 创建构造函数
// TODO: 实现 printProfile() 方法
// TODO: 实现 updateEmail() 方法
// TODO: 实现 getDisplayName() 方法
}基础知识中的所有课
自己练习: Dart 在线编译器