Optional Parameters in Dart
In Dart, optional parameters can be defined by using brackets [ ] to let the compiler know these parameters are optional.
Here [String? optional] is an optional parameter. Also note, that whenever you have an optional parameter, it always can be null.
myFunction can now be executed properly by only passing in 1 parameter value. The second, optional, is completely optional of course an it’s value will be null if nothing is passed in.
void main() {
myFunction('hello');
// Value: hello
// Optional: null
}
void myFunction(String value, [String? optional]) {
print('Value: $value');
print('Optional: $optional');
}
We can also specify another way of declaring an optional parameter using an optional named parameter. Named parameters are either required, meaning they must have values, or not required, meaning they are optional.
To declare a named parameter is done simply like so:
// number here is optional and is also marked nullable.
// text is of course required, and cannot ever be null since it is declared as String
void myNamedParameterFunction({ required String text, int? number }) {
print('Text: $text');
print('Number: $number');
}
void main() {
myNamedParameterFunction(text: 'hello');
}
Above, text is declared as a name parameter with the String value of ‘hello’. Number of course is completely optional, because it can be null.
If we wanted to, we could declare number to have a default value so it will never be null.
// Here number is optional but will also never be null.
// It will always default to 0;
void myNamedParameterFunction({ required String text, int number = 0 }) {
print('Text: $text');
print('Number: $number');
}
Thanks for reading! 😎👋🏽