Menu
Coddy logo textTech

Recap - Handling Null Safely

Part of the Fundamentals section of Coddy's Dart journey — lesson 82 of 94.

challenge icon

Challenge

Easy

You're building a user profile system for a mobile app. Create a UserProfile class that demonstrates your understanding of Dart's null safety features.

Implement a class UserProfile with the following:

  1. Non-nullable properties (must always have a value):
    • id of type int
    • createdDate of type String
  2. Nullable properties (can be null at initialization):
    • name of type String?
    • email of type String?
    • age of type int?
  3. Late-initialized property:
    • displayName of type String, declared using the late keyword
  4. Constructor:
    • Accepts id and createdDate as required parameters
    • Initializes displayName to "Guest"
  5. Method: <strong>void printProfile()</strong> Prints the user profile with the following format:

    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>
    • Updates the email property with the new value.
  7. Method: <strong>String getDisplayName()</strong>
    • If name is not null, sets displayName = name! (using null assertion operator)
    • Returns the current value of displayName

Important: After updating the name property, you must call getDisplayName() to update the displayName field before printing the profile again.

Complete the code to create a profile, update it, and display the information as shown in the expected output.

Try it yourself

void main() {
  // Create a user profile
  final profile = UserProfile(1, 'today');
  
  // Print initial profile
  profile.printProfile();
  
  // Update profile
  profile.name = 'John Doe';
  profile.updateEmail('john@example.com');
  profile.age = 30;
  
  // Update display name and print updated profile
  profile.getDisplayName(); // Call this to update displayName
  profile.printProfile();
}

class UserProfile {
  // TODO: Add properties (id, createdDate, name, email, age, displayName)
  
  // TODO: Create constructor
  
  // TODO: Implement printProfile() method
  
  // TODO: Implement updateEmail() method
  
  // TODO: Implement getDisplayName() method
}

All lessons in Fundamentals