A function gives a task a name. Parameters are its inputs. A return value is its result. The same rule can then be used in several places. We calculate distance travelled. The function does not print anything. It returns a number, which makes it testable without an interface.
01Understand the signature
int before distance is the return type. previous and current are named parameters. required requires the caller to provide them. return ends the call and returns its result.
int distance({required int previous, required int current}) {
return current - previous;
}
void main() {
final result = distance(previous: 64820, current: 64920);
print('$result km');
}
Run / check
dart run functions.dart02Encapsulate a domain rule
The subtraction is simple, but the name and parameters explain its meaning. Later, services distinguish ordinary progress, corrections and counter replacements. A lower reading must not silently become an ordinary distance.
03Call a function
main calls distance(previous: 64820, current: 64920). Named arguments can appear in any order. The result is then used in print. The local name previous exists only during the function call.
Output: 100 km
Your exercise
Write a function called euros that takes an amount in cents and divides it by 100.
Show the solution and explanation
double euros(int cents) => cents / 100 is a short function form. euros(12990) returns 129.9. Unlike named parameters, positional parameters are supplied in order.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.