Set default value for parameter in Dart
Flutter Tutorial
Install Flutter in Win/Linux/Mac
Flutter Widgets:
Bottom Navigation Bar in Flutter
Auto Close Keyboard in Flutter
Screen size handling in Flutter
Flutter REST API
Flutter Advance
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips
Interview Questions
To set default values for parameters in Dart , you can use assignment operator (=).
Here in below example we use String prefix = ‘Default’
void printMessage(String message, {String prefix = 'Default'}) {
print('$prefix: $message');
}
void main() {
printMessage('Hello'); // Output: Default: Hello
printMessage('Hi', prefix: 'Custom'); // Output: Custom: Hi
}
Example II
In this example calculateRectangleArea pass two parameters width and height
double calculateRectangleArea({double width = 5.0, double height = 3.0}) {
return width * height;
}
void main() {
//In this we pass no value so it will use defaut value
double area1 = calculateRectangleArea(); // Uses default values (5.0 and 3.0)
//In this we pass width and height output will be different
double area2 = calculateRectangleArea(width: 8.0, height: 4.0); // Custom values
print('Area 1: $area1'); // Output: Area 1: 15.0
print('Area 2: $area2'); // Output: Area 2: 32.0
}