Function parameters in Dart allow you to pass data into functions, making them more flexible and reusable. Understanding different types of parameters is crucial for writing efficient Dart code.
Positional parameters are the most basic type. They're defined in a specific order and must be provided in that same order when calling the function.
void greet(String name, int age) {
print('Hello, $name! You are $age years old.');
}
// Usage
greet('Alice', 30);
To make positional parameters optional, enclose them in square brackets. Optional parameters are placed at the end of the parameter list.
String introduce(String name, [String? title]) {
return title != null ? '$title $name' : name;
}
// Usage
print(introduce('Bob')); // Output: Bob
print(introduce('Alice', 'Dr.')); // Output: Dr. Alice
Named parameters allow you to specify arguments by name, providing more clarity and flexibility. They're defined using curly braces.
void createUser({required String name, int age = 18, String? email}) {
print('Name: $name, Age: $age, Email: ${email ?? "Not provided"}');
}
// Usage
createUser(name: 'Charlie', age: 25, email: 'charlie@example.com');
createUser(name: 'David');
You can assign default values to both optional positional and named parameters. This is useful when you want to provide a fallback value if an argument isn't supplied.
void showInfo(String name, {int age = 30, String country = 'Unknown'}) {
print('$name is $age years old and from $country');
}
// Usage
showInfo('Eve'); // Uses default values
showInfo('Frank', age: 40, country: 'Canada');
required
keyword for named parameters that must be provided.Dart offers advanced techniques for working with function parameters, including:
Mastering Dart function parameters is essential for creating flexible and maintainable code. They form the foundation for more advanced concepts like Dart Closures and Dart Arrow Functions.
Function parameters in Dart provide a powerful way to create versatile and reusable code. By understanding the different types of parameters and when to use them, you can write more efficient and readable Dart programs. Practice using these concepts in your projects to solidify your understanding and improve your Dart programming skills.