Menu
Coddy logo textTech

まとめ - Null を安全に扱う

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

challenge icon

チャレンジ

簡単

モバイルアプリ用のユーザープロファイルシステムを構築しています。Dart の null safety 機能についての理解を示す UserProfile class を作成してください。

次の内容を持つ UserProfile class を Implement してください。

  1. Non-nullable properties(常に値を持つ必要があります):
    • intid
    • StringcreatedDate
  2. Nullable properties(初期化時に null にできます):
    • String?name
    • String?email
    • int?age
  3. Late-initialized property
    • StringdisplayNamelate keyword を使用して宣言します
  4. Constructor
    • 必須パラメーターとして idcreatedDate を受け取ります
    • displayName"Guest" に初期化します
  5. method: <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. method: <strong>void updateEmail(String? newEmail)</strong>
    • email property を新しい値で更新します。
  7. method: <strong>String getDisplayName()</strong>
    • name が null でない場合、displayName = name!(null assertion operator を使用)を設定します
    • displayName の現在の値を返します

重要:name property を更新した後、プロファイルを再度出力する前に getDisplayName() を呼び出して displayName field を更新する必要があります。

プロファイルを作成して更新し、期待される出力に示されているとおりに情報を表示するコードを完成させてください。

自分で試してみよう

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オンラインコンパイラ