まとめ - Null を安全に扱う
CoddyのDartジャーニー「基礎」セクションの一部。レッスン 82/94。
チャレンジ
簡単モバイルアプリ用のユーザープロファイルシステムを構築しています。Dart の null safety 機能についての理解を示す UserProfile class を作成してください。
次の内容を持つ UserProfile class を Implement してください。
- Non-nullable properties(常に値を持つ必要があります):
- 型
intのid - 型
StringのcreatedDate
- 型
- Nullable properties(初期化時に null にできます):
- 型
String?のname - 型
String?のemail - 型
int?のage
- 型
- Late-initialized property:
- 型
StringのdisplayName。latekeyword を使用して宣言します
- 型
- Constructor:
- 必須パラメーターとして
idとcreatedDateを受け取ります displayNameを"Guest"に初期化します
- 必須パラメーターとして
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> -------------------- method:
<strong>void updateEmail(String? newEmail)</strong>emailproperty を新しい値で更新します。
- 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オンラインコンパイラ