Menu
CoddyTech

回顾:用户资料系统

本课属于 Coddy Dart 学习旅程的“面向对象编程”单元。第 29 课,共 110 课。

challenge icon

挑战

简单

让我们构建一个完整的用户资料系统,把你在本章学到的所有空安全概念结合起来。你将创建一个管理用户账号的系统,其中包含必填信息和可选详情。

你将把代码分成两个文件:

  • user_profile.dart:定义一个表示用户账号的 UserProfile 类。想一想哪些信息是必需的(例如用户名),哪些是可选的(例如个人简介或电话号码)。你的类应包含:
    • 一个不可为空的 String username,每个用户都必须有用户名
    • 一个不可为空的 String email,每个用户都必须有电子邮箱
    • 一个可为空的 String? displayName,用户可能更愿意显示其他名称
    • 一个可为空的 String? bio,不是每个人都会填写个人简介
    • 一个可为空的 int? age,年龄是可选的个人信息
    • 一个使用命名参数的构造函数,并将 username 和 email 设为 required
    • 一个 getDisplayIdentity() 方法,如果显示名称已设置,就返回显示名称,否则使用 ?? 返回用户名
    • 一个 getBioPreview() 方法,如果个人简介存在且长度超过 20 个字符,就返回前 20 个字符并在后面加上 ...;如果长度不超过 20 个字符,就返回完整的个人简介;如果没有个人简介,就返回 null(使用 ?. 安全访问)
    • 一个 setDefaultBio() 方法,仅当个人简介当前为 null 时,才使用 ??= 将其设为 'Hello, I am new here!'
    • 一个 printProfile() 方法,用于显示用户的完整资料
  • main.dart:导入你的用户资料类,并创建几个用户,以展示各种空安全功能:
    • 创建一个用户名为 'alice_dev'、电子邮箱为 'alice@code.com' 的用户,然后将显示名称设为 'Alice',将个人简介设为 'Software developer passionate about clean code and testing',并将年龄设为 28
    • 创建一个用户名为 'bob_builder'、电子邮箱为 'bob@build.io' 的用户,然后只将显示名称设为 'Bob'
    • 创建一个用户名为 'charlie99'、电子邮箱为 'charlie@mail.net' 的用户(所有可选字段都保持为 null)
    • 对这三个用户都调用 setDefaultBio()
    • 按顺序处理每个用户,调用 printProfile(),然后打印 Identity: [getDisplayIdentity()],再打印 Bio preview: [getBioPreview()]

printProfile() 方法应按以下格式打印:

===== User Profile =====
Username: [username]
Email: [email]
Display Name: [displayName or "Not set"]
Bio: [bio or "No bio"]
Age: [age or "Not specified"]

请注意,Alice 的个人简介在调用 setDefaultBio() 后保持不变,因为它已经有值;而 Charlie 则会被设为默认个人简介。还要留意,个人简介预览会截断 Alice 较长的个人简介,但会完整显示 Charlie 较短的默认个人简介。

预期输出:

===== User Profile =====
Username: alice_dev
Email: alice@code.com
Display Name: Alice
Bio: Software developer passionate about clean code and testing
Age: 28
Identity: Alice
Bio preview: Software developer p...
===== User Profile =====
Username: bob_builder
Email: bob@build.io
Display Name: Bob
Bio: Hello, I am new here!
Age: Not specified
Identity: Bob
Bio preview: Hello, I am new here!
===== User Profile =====
Username: charlie99
Email: charlie@mail.net
Display Name: Not set
Bio: Hello, I am new here!
Age: Not specified
Identity: charlie99
Bio preview: Hello, I am new here!

亲手试试

import 'user_profile.dart';

void main() {
  // TODO: 创建用户 'alice_dev',邮箱为 'alice@code.com'
  // 将 displayName 设为 'Alice'
  // 将 bio 设为 'Software developer passionate about clean code and testing'
  // 将 age 设为 28
  
  // TODO: 创建用户 'bob_builder',邮箱为 'bob@build.io'
  // 只将 displayName 设为 'Bob'
  
  // TODO: 创建用户 'charlie99',邮箱为 'charlie@mail.net'
  // 将所有可选字段保留为 null
  
  // TODO: 对这三个用户都调用 setDefaultBio()
  
  // TODO: 按顺序对每个用户(alice、bob、charlie)执行以下操作:
  // 1. 调用 printProfile()
  // 2. 打印 "Identity: [getDisplayIdentity()]"
  // 3. 打印 "Bio preview: [getBioPreview()]"
}

面向对象编程中的所有课

自己练习: Dart 在线编译器