Menu
CoddyTech

回顾:安全处理空值

本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 82 课,共 94 课。

challenge icon

挑战

简单

你正在为移动应用构建用户资料系统。创建一个 UserProfile 类,展示你对 Dart 空安全功能的理解。

实现一个 UserProfile 类,包含以下内容:

  1. 不可空属性(必须始终有值):
    • 类型为 int 的 id
    • 类型为 String 的 createdDate
  2. 可空属性(初始化时可以为 null):
    • 类型为 String? 的 name
    • 类型为 String? 的 email
    • 类型为 int? 的 age
  3. 延迟初始化属性:
    • 类型为 String 的 displayName,使用 late 关键字声明
  4. 构造函数:
    • 将 id 和 createdDate 作为必需参数
    • 将 displayName 初始化为 "Guest"
  5. 方法: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>
    -------------------
  6. 方法:void updateEmail(String? newEmail)
    • 使用新值更新 email 属性。
  7. 方法: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 在线编译器