Functions in Dart are very similar to function definitions in most C style languages.
In addition to the main function, you can create your own function.
To define a function, you will need to define a return type, a function name, and a parameter list.
// general form
<return data type> function_name(<parameter list>) {
// function body
}
// example
void foo() {
print("Inside of foo - a useless function");
}
int add(int v1, int v2) {
return v1 + v2;
}
Now a function in Dart is a form of an object. That means, you can pass a function into another function, and store them in variables.
Overloading and Optional Parameters
Now in a lot of newer languages, you can overload a function. However, Dart doesn’t allow that. Instead, like with Python, you can define optional parameters by putting them in square brackets. They can either be nullable, or given a default value.
Notice, if you have more than one optional parameter, you only have one square bracket, but, you can separate the multiple optional parameters with commas.
int addIt(int v1, int v2, [int v3 = 0, int v4 = 0]) {
return v1 + v2 + v3 = v4;
}
Functions in Dart was originally found on Access 2 Learn