Junior
What are named parameters in Dart?
sobes.tech AI
Answer from AI
Named parameters are optional parameters of functions and constructors in the Dart language, which are passed by name instead of position. They make function calls more readable and do not require strict adherence to argument order.
They are declared inside curly braces {}. To make a named parameter mandatory, the required keyword is used.
Example of using named parameters:
// Defining a function with named parameters
void greet({String? name, int? age}) {
print('Hello, my name is $name and I am $age years old.');
}
// Calling the function with named parameters (order does not matter)
void main() {
greet(name: 'Alice', age: 30);
greet(age: 25, name: 'Bob');
greet(name: 'Charlie'); // age will be null
}
Example of using a mandatory named parameter:
// Defining a function with a mandatory named parameter
void displayInfo({required String id, String? description}) {
print('ID: $id');
if (description != null) {
print('Description: $description');
}
}
// Calling the function with a mandatory named parameter
void main() {
displayInfo(id: 'User123');
displayInfo(id: 'ProductXYZ', description: 'Great product.');
// displayInfo(); // Error: required parameter 'id' must be provided.
}
Advantages of using named parameters:
- Improved readability: The purpose of each argument is clear from its name.
- Flexibility: The order of arguments does not matter.
- Convenience: Easily add new optional parameters without breaking existing call code.
- Safety: The compiler can check the passing of required named parameters at compile time.