Menu
Coddy logo textTech

Required Named Parameters

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

The required keyword forces named parameters to be provided when calling a function. Without it, named parameters are optional by default.

Create a function with required named parameters:

void createUser({required String name, required int age}) {
  print('User created: $name, $age years old');
}

Call the function with all required parameters:

void main() {
  createUser(name: 'Alex', age: 30);
}

After executing the above code, the output will be:

User created: Alex, 30 years old

If you try to omit a required parameter, Dart will show an error:

// This would cause an error:
// createUser(name: 'Alex'); // Missing required parameter 'age'
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the required keyword with named parameters in Dart. The required keyword ensures that a named parameter must be provided when calling a function.

Complete the createUserProfile function by adding the required keyword to make both the name and age parameters required.

Cheat sheet

The required keyword forces named parameters to be provided when calling a function. Without it, named parameters are optional by default.

Create a function with required named parameters:

void createUser({required String name, required int age}) {
  print('User created: $name, $age years old');
}

Call the function with all required parameters:

createUser(name: 'Alex', age: 30);

Omitting a required parameter will cause a compilation error.

Try it yourself

void main() {
  // This function call is already set up for you
  String profile = createUserProfile(name: 'Alice', age: 30);
  print(profile);
  
  // Uncomment this line to see what happens when required parameters are missing
  // String invalidProfile = createUserProfile(name: 'Bob');
}

// TODO: Add the 'required' keyword to make both parameters required
String createUserProfile({String name, int age}) {
  return 'User Profile: $name, $age years old';
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals