Dart Function Parameters
Understanding different parameter types in Dart
📋 What are Function Parameters?
Function parameters are inputs that functions receive to perform their tasks. Dart supports required, optional, named, and default parameters to make functions flexible and easy to use.
// Function with required parameters
void greet(String name, int age) {
print('Hello $name, you are $age years old');
}
Parameter Types
Required Parameters
Must be provided when calling
void greet(String name) {
print('Hello $name');
}
Optional Parameters
Can be omitted when calling
void greet(String name, [int? age]) {
print('Hello $name');
}
Named Parameters
Called by parameter name
void greet({String? name, int? age}) {
print('Hello $name');
}
Default Parameters
Have default values
void greet([String name = 'Guest']) {
print('Hello $name');
}
🔹 Required Parameters
Basic parameters that must be provided:
void main() {
// Function with required parameters
void calculateArea(double width, double height) {
double area = width * height;
print('Area: $area');
}
void displayPersonInfo(String name, int age, String city) {
print('Name: $name, Age: $age, City: $city');
}
// Must provide all required parameters
calculateArea(10.0, 5.0);
displayPersonInfo('Alice', 25, 'New York');
// This would cause an error:
// calculateArea(10.0); // Missing height parameter
}
Output:
Area: 50.0
Name: Alice, Age: 25, City: New York
🔹 Optional Positional Parameters
Parameters enclosed in square brackets [] are optional:
void main() {
// Function with optional parameters
void greetPerson(String name, [String? title, int? age]) {
String greeting = 'Hello';
if (title != null) greeting += ' $title';
greeting += ' $name';
if (age != null) greeting += ', age $age';
print(greeting);
}
// Different ways to call the function
greetPerson('John'); // Only required parameter
greetPerson('Jane', 'Dr.'); // With title
greetPerson('Bob', 'Mr.', 30); // With title and age
greetPerson('Alice', null, 25); // Skip title, provide age
}
Output:
Hello John
Hello Dr. Jane
Hello Mr. Bob, age 30
Hello Alice, age 25
🔹 Named Parameters
Parameters enclosed in curly braces {} can be called by name:
void main() {
// Function with named parameters
void createUser({String? name, int? age, String? email, bool isActive = true}) {
print('Creating user:');
print(' Name: ${name ?? 'Unknown'}');
print(' Age: ${age ?? 'Not specified'}');
print(' Email: ${email ?? 'Not provided'}');
print(' Active: $isActive');
print('---');
}
// Call with named parameters (order doesn't matter)
createUser(name: 'Alice', age: 25);
createUser(email: '[email protected]', name: 'Bob', isActive: false);
createUser(age: 30);
createUser(); // All parameters are optional
}
Output:
Creating user:
Name: Alice
Age: 25
Email: Not provided
Active: true
---
Creating user:
Name: Bob
Age: Not specified
Email: [email protected]
Active: false
---
🔹 Required Named Parameters
Use the 'required' keyword to make named parameters mandatory:
void main() {
// Function with required named parameters
void bookFlight({
required String from,
required String to,
required DateTime date,
String? passengerName,
int passengers = 1
}) {
print('Flight Booking:');
print(' From: $from');
print(' To: $to');
print(' Date: ${date.toString().split(' ')[0]}');
print(' Passengers: $passengers');
if (passengerName != null) {
print(' Passenger: $passengerName');
}
}
// Must provide required named parameters
bookFlight(
from: 'New York',
to: 'London',
date: DateTime(2024, 6, 15),
passengerName: 'John Doe'
);
// This would cause an error:
// bookFlight(from: 'Paris'); // Missing required parameters
}
Output:
Flight Booking:
From: New York
To: London
Date: 2024-06-15
Passengers: 1
Passenger: John Doe
🔹 Default Parameter Values
Provide default values for optional parameters:
void main() {
// Function with default values
void printMessage(String message, [String prefix = 'INFO', bool timestamp = false]) {
String output = '[$prefix] $message';
if (timestamp) {
output = '${DateTime.now().toString().split('.')[0]} $output';
}
print(output);
}
// Named parameters with defaults
void configureApp({
String theme = 'light',
bool notifications = true,
int maxUsers = 100,
String language = 'en'
}) {
print('App Configuration:');
print(' Theme: $theme');
print(' Notifications: $notifications');
print(' Max Users: $maxUsers');
print(' Language: $language');
}
// Using default values
printMessage('Application started');
printMessage('Error occurred', 'ERROR');
printMessage('Debug info', 'DEBUG', true);
configureApp();
configureApp(theme: 'dark', maxUsers: 500);
}
Output:
[INFO] Application started
[ERROR] Error occurred
2024-01-15 10:30:45 [DEBUG] Debug info
App Configuration:
Theme: light
Notifications: true
Max Users: 100
Language: en
🔹 Parameter Best Practices
When to Use Each Type:
- Required: Essential data that function needs
- Optional Positional: Additional data in specific order
- Named: Many parameters or when order doesn't matter
- Required Named: Essential parameters with clear names
Design Guidelines:
- Limit parameters: Too many parameters make functions hard to use
- Use meaningful names: Parameter names should be descriptive
- Group related parameters: Consider using classes for complex data
- Provide sensible defaults: Make common use cases easy