Bird
Raised Fist0
Fluttermobile~20 mins

Constructors and named parameters in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User Profile
A simple screen that shows a user profile card using a class with named parameters in its constructor.
Target UI
┌─────────────────────────────┐
│        User Profile          │
├─────────────────────────────┤
│ Name: John Doe              │
│ Age: 30                    │
│ Email: john@example.com     │
└─────────────────────────────┘
Create a User class with named parameters for name, age, and email.
Use a constructor with required named parameters.
Display the user information in a card on the screen.
Starter Code
Flutter
import 'package:flutter/material.dart';

class User {
  // TODO: Add named parameters constructor here
}

class UserProfileScreen extends StatelessWidget {
  final User user = User(); // TODO: Pass named parameters here

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('User Profile')),
      body: Center(
        child: Card(
          margin: EdgeInsets.all(16),
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Name: '), // TODO: Show user name
                Text('Age: '),  // TODO: Show user age
                Text('Email: '), // TODO: Show user email
              ],
            ),
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: UserProfileScreen()));
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class User {
  final String name;
  final int age;
  final String email;

  User({required this.name, required this.age, required this.email});
}

class UserProfileScreen extends StatelessWidget {
  final User user = User(name: 'John Doe', age: 30, email: 'john@example.com');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('User Profile')),
      body: Center(
        child: Card(
          margin: EdgeInsets.all(16),
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Name: ${user.name}'),
                Text('Age: ${user.age}'),
                Text('Email: ${user.email}'),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: UserProfileScreen()));
}

We created a User class with a constructor that uses named parameters. Each parameter is marked required to ensure the caller provides all values. This makes the code clear and safe.

In UserProfileScreen, we create a User object by passing values with parameter names. Then we display these values in the UI using string interpolation inside Text widgets.

This approach helps beginners understand how named parameters work in Dart constructors and how to use them in Flutter widgets.

Final Result
Completed Screen
┌─────────────────────────────┐
│        User Profile          │
├─────────────────────────────┤
│ Name: John Doe              │
│ Age: 30                    │
│ Email: john@example.com     │
└─────────────────────────────┘
The screen shows a card with the user's name, age, and email.
No interactive elements on this screen.
Stretch Goal
Add a button that shows a dialog to update the user's email using named parameters.
💡 Hint
Use a StatefulWidget to hold the user state and a TextField inside an AlertDialog to get new email input.

Practice

(1/5)
1. What is the main purpose of named parameters in Flutter constructors?
easy
A. To prevent object creation
B. To force all arguments to be positional
C. To make constructors private
D. To make arguments optional and improve code readability

Solution

  1. Step 1: Understand named parameters

    Named parameters are enclosed in curly braces and can be optional or required, making code easier to read.
  2. Step 2: Identify their purpose in constructors

    They allow passing arguments by name, improving clarity and safety by avoiding positional mistakes.
  3. Final Answer:

    To make arguments optional and improve code readability -> Option D
  4. Quick Check:

    Named parameters = optional and readable [OK]
Hint: Named parameters use braces and improve clarity [OK]
Common Mistakes:
  • Thinking named parameters force positional arguments
  • Believing named parameters prevent object creation
  • Confusing named parameters with private constructors
2. Which of the following is the correct syntax for a Flutter constructor with named parameters?
easy
A. MyClass({this.name, this.age});
B. MyClass(this.name, this.age);
C. MyClass[name, age];
D. MyClass(name: this.name, age: this.age);

Solution

  1. Step 1: Identify named parameter syntax

    Named parameters are declared inside curly braces in the constructor parameter list.
  2. Step 2: Match syntax to options

    MyClass({this.name, this.age}); uses curly braces with this.name and this.age, which is correct syntax.
  3. Final Answer:

    MyClass({this.name, this.age}); -> Option A
  4. Quick Check:

    Named parameters use curly braces { } [OK]
Hint: Look for curly braces around parameters [OK]
Common Mistakes:
  • Using square brackets instead of curly braces
  • Forgetting curly braces for named parameters
  • Using colon syntax incorrectly in constructor declaration
3. What will be the output of this Flutter code?
class Person {
  String name;
  int age;
  Person({required this.name, this.age = 30});
}

void main() {
  var p = Person(name: 'Anna');
  print('${p.name} is ${p.age} years old');
}
medium
A. Anna is 30 years old
B. Anna is null years old
C. Error: Missing required parameter age
D. Anna is 0 years old

Solution

  1. Step 1: Analyze constructor parameters

    The constructor requires name and has an optional age with default 30.
  2. Step 2: Check object creation and print output

    Person is created with name 'Anna' only, so age defaults to 30. The print shows 'Anna is 30 years old'.
  3. Final Answer:

    Anna is 30 years old -> Option A
  4. Quick Check:

    Default age = 30 used [OK]
Hint: Default values fill missing optional named parameters [OK]
Common Mistakes:
  • Assuming missing optional parameters cause errors
  • Thinking default values are ignored
  • Confusing required and optional parameters
4. Identify the error in this Flutter constructor code:
class Car {
  String model;
  int? year;
  Car({this.model, this.year});
}

void main() {
  var c = Car(model: 'Tesla');
  print(c.year.toString());
}
medium
A. model is missing and causes compile error
B. year is null and calling toString() causes runtime error
C. No error, code runs fine
D. Constructor syntax is invalid

Solution

  1. Step 1: Check constructor parameters and defaults

    Both model and year are optional named parameters without defaults, so year can be null.
  2. Step 2: Analyze print statement

    Calling toString() on null year does NOT cause runtime error because toString() is defined on nullable int? and returns 'null' string.
  3. Final Answer:

    No error, code runs fine -> Option C
  4. Quick Check:

    toString() on null returns 'null' string [OK]
Hint: Optional parameters without defaults can be null but toString() handles null safely [OK]
Common Mistakes:
  • Assuming missing optional parameters have default values
  • Ignoring null safety and runtime errors
  • Thinking constructor syntax is wrong here
5. You want to create a Flutter class Book with a required named parameter title and an optional named parameter author with default 'Unknown'. Which constructor is correct?
hard
A. Book(this.title, {this.author = 'Unknown'});
B. Book({required this.title, this.author = 'Unknown'});
C. Book({this.title, required this.author = 'Unknown'});
D. Book({this.title = 'Unknown', required this.author});

Solution

  1. Step 1: Identify required and optional named parameters

    Required named parameters use 'required' keyword inside curly braces; optional can have default values.
  2. Step 2: Match correct syntax

    Book({required this.title, this.author = 'Unknown'}); correctly marks title as required and author as optional with default 'Unknown'.
  3. Final Answer:

    Book({required this.title, this.author = 'Unknown'}); -> Option B
  4. Quick Check:

    Required + optional with default = correct syntax [OK]
Hint: Use 'required' inside braces for required named params [OK]
Common Mistakes:
  • Placing required outside braces
  • Assigning default to required parameter
  • Mixing positional and named parameters incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard