Dart: Function parameters
This article is part of a series on How to start creating mobile applications for Android or iOS using Dart & Flutter.
The simplest way to use parameters is by specifying the type and name of the parameter. With this approach, you will need to pass all the arguments when calling the function.
void main() {
// x = 2, y = 4
printSum(2, 4);
}
void printSum(int x, int y) {
print('Sum = ${x + y}');
}Optional parameters
Get Arte Bi’s stories in your inbox
Join Medium for free to get updates from this writer.
You can make one parameter or all of them optional. However, you will still need to adhere to the order of argument specification. To make a parameter optional, you need to enclose it in square brackets and provide a default value.
void main() {
// x = 1, y = 2, k = 3
printSum(1, 2, 3);
// x = 1, y = 2, k = 10
printSum(1, 2);
}
// 'k' is optional
void printSum(int x, int y, [int k = 10]) {
print('Sum = ${x + y + k}');
}
// Result will be:
// Sum = 6
// Sum = 13void main() {
// x = 1, y = 2, k = 3
printSum(1, 2, 3);
// x = 1, y = 2, k = 10
printSum(1, 2);
// x = 1, y = 20, k = 10
printSum(1);
}
// 'y' and 'k' is optional
void printSum(int x, [int y = 20, int k = 10]) {
print('Sum = ${x + y + k}');
}
// Result will be:
// Sum = 6
// Sum = 13
// Sum = 31Named parameters
Named parameters are optional, but you must provide a default value or make the type nullable. In functions, named parameters are enclosed in curly braces. When calling the function, before passing the parameter you must specify its name; the order of arguments can be arbitrary.
void main() {
// x = 5, y = 6, k = 8
printSum(k: 8, x: 5, y: 6);
// x = 1, y = 3, k = null
printSum(y: 3, x: 1);
// x = 7, y = 20, k = null
printSum(x: 7);
}
void printSum({int x = 5, int y = 20, int? k}) {
if (k == null) {
print('Sum = ${x + y}');
} else {
print('Sum = ${x + y + k}');
}
}
// Result will be
// Sum = 19
// Sum = 4
// Sum = 27If you want a named parameter to become mandatory, you need to label it with the required keyword. In this case, you don’t need to specify a default value.
void main() {
printSum(x: 7);
}
// 'y' is optional and 'x' is required
void printSum({required int x, int y = 20}) {
print('Sum = ${x + y}');
}
// Result will be:
// Sum = 27








