Functions
Dart is a true object-oriented language, so even functions are objectsand have a type, Function.This means that functions can be assigned to variables or passed as argumentsto other functions. You can also call an instance of a Dart class as ifit were a function. For details, see Callable classes.
Here’s an example of implementing a function:
bool isNoble(int atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
Although Effective Dart recommendstype annotations for public APIs,the function still works if you omit the types:
isNoble(atomicNumber) {
return _nobleGases[atomicNumber] != null;
}
For functions that contain just one expression, you can use a shorthandsyntax:
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;
The => expr
syntax is a shorthand for{ return expr; }
. The =>
notationis sometimes referred to as arrow syntax.
Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression.
A function can have two types of parameters: required and optional.The required parameters are listed first, followed by any optional parameters.Optional parameters can be named or positional.
Note: Some APIs — notably Flutter widget constructors — use only named parameters, even for parameters that are mandatory. See the next section for details.