Menu
Coddy logo textTech

まとめ - Null を安全に扱う

CoddyのDartジャーニー「基礎」セクションの一部 — レッスン 82/94。

challenge icon

チャレンジ

簡単

モバイルアプリ向けのユーザー プロファイル システムを構築してください。UserProfile クラスを作成し、Dart の null 安全性機能に対する理解を示してください。

UserProfile クラスを実装し、次の要素を含めてください:

  1. 非 nullable プロパティ(常に値が必要です):
    • id の型は int
    • createdDate の型は String
  2. Nullable プロパティ(初期化時に null 可能です):
    • name の型は String?
    • email の型は String?
    • age の型は int?
  3. 遅延初期化プロパティ
    • displayName の型は String で、late キーワードを使用して宣言
  4. コンストラクタ
    • idcreatedDate を必須パラメータとして受け取る
    • displayName"Guest" に初期化
  5. メソッド: <strong>void printProfile()</strong> ユーザー プロファイルを次の形式で出力します:

    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. メソッド: <strong>void updateEmail(String? newEmail)</strong>
    • email プロパティを新しい値で更新します。
  7. メソッド: <strong>String getDisplayName()</strong>
    • name が null でない場合、displayName = name! を設定(null 断定演算子を使用)
    • 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() メソッドを実装
}

基礎のすべてのレッスン