In Dart - as in many other languages - there is more than one way to declare a function. The question is, are there any differences aka "when should I use which"?
void foo(int i) {
print('i = $i');
}
void main() {
void Function(int) bar = (int j) {
print('j = $j');
};
foo(1);
bar(2);
}
Is there any difference in the declaration of foo
or bar
other than the fact that bar
can be overwritten?
Functions can be introduced by
In terms of Dart specification there is 2 differences between function literals (aka anonymous function) and other declarations
If you prefer to keep type safety, you will have to write long declaration.
Consider this example:
String foo(int i, {bool b}) => '$b $i'; // return type declared
final bar = (int i, {bool b}) => '$b $i'; // return type could not be infered
final String Function(int i, {bool b}) bar = (i, {b}) => '$b $i'; // return type infered
From my perspective
bar
isn't as readable as foo
declarationPS If I missed anything - please edit my answer or reach me in comments