Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
Optional Parameters
Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function.
We have three types of optional parameters in Dart −
1 | Optional Positional Parameter :-To specify optional positional parameters, use square [] brackets. |
2 | Optional named parameter :-Unlike positional parameters, the parameter's name must be specified while the value is being passed. Curly brace {} can be used to specify optional named parameters. |
3 | Optional Parameters with Default Values :-Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. |
Recursive Dart Functions
Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
Example
void main() {
print(factorial(6));
}
factorial(number) {
if (number <= 0) {
// termination case
return 1;
} else {
return (number * factorial(number - 1));
// function invokes itself
}
}
It should produce the following output −
720
Lambda Functions
Lambda functions are a concise mechanism to represent functions. These functions are also called as Arrow functions.
Syntax
[return_type]function_name(parameters)=>expression;
Example
void main() {
printMsg();
print(test());
}
printMsg()=>
print("hello");
int test()=>123;
// returning function
It should produce the following output −
hello 123
Named parameters
Named parameters are optional unless they’re explicitly marked as required
.
When defining a function, use {param1, param2, …}
to specify named parameters. If you don’t provide a default value or mark a named parameter as required
, their types must be nullable as their default value will be null
:
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool? bold, bool? hidden}) {...}
When calling a function, you can specify named arguments using paramName: value
. For example:
enableFlags(bold: true, hidden: false);
To define a default value for a named parameter besides null
, use =
to specify a default value. The specified value must be a compile-time constant. For example:
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}
// bold will be true; hidden will be false.
enableFlags(bold: true);
If you instead want a named parameter to be mandatory, requiring callers to provide a value for the parameter, annotate them with required
:
const Scrollbar({super.key, required Widget child});
If someone tries to create a Scrollbar
without specifying the child
argument, then the analyzer reports an issue.
You might want to place positional arguments first, but Dart doesn’t require it. Dart allows named arguments to be placed anywhere in the argument list when it suits your API:
repeat(times: 2, () {
...
});
Optional positional parameters
Wrapping a set of function parameters in []
marks them as optional positional parameters. If you don’t provide a default value, their types must be nullable as their default value will be null
:
String say(String from, String msg, [String? device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
Here’s an example of calling this function without the optional parameter:
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
And here’s an example of calling this function with the third parameter:
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');
To define a default value for an optional positional parameter besides null
, use =
to specify a default value. The specified value must be a compile-time constant. For example:
String say(String from, String msg, [String device = 'carrier pigeon']) {
var result = '$from says $msg with a $device';
return result;
}
assert(say('Bob', 'Howdy') == 'Bob says Howdy with a carrier pigeon');
The main() function
Every app must have a top-level main()
function, which serves as the entrypoint to the app. The main()
function returns void
and has an optional List<String>
parameter for arguments.
Here’s a simple main()
function:
void main() {
print('Hello, World!');
}
Here’s an example of the main()
function for a command-line app that takes arguments:
// Run the app like this: dart args.dart 1 test
void main(List<String> arguments) {
print(arguments);
assert(arguments.length == 2);
assert(int.parse(arguments[0]) == 1);
assert(arguments[1] == 'test');
}
You can use the args library to define and parse command-line arguments.
Functions as first-class objects
You can pass a function as a parameter to another function. For example:
void printElement(int element) {
print(element);
}
var list = [1, 2, 3];
// Pass printElement as a parameter.
list.forEach(printElement);
You can also assign a function to a variable, such as:
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
assert(loudify('hello') == '!!! HELLO !!!');
Return values
All functions return a value. If no return value is specified, the statement return null;
is implicitly appended to the function body.
foo() {}
assert(foo() == null);
To return multiple values in a function, aggregate the values in a record.
(String, int) foo() {
return ('something', 42);
}