So let's have a look at how these actually work!
Dart has a formal specification documented and you can have a look at it by clicking here. A function in Dart has to have a few qualities which are:
- return type (optional but recommended)
- name (required)
- parenthesis right after the name (required)
- a list of parameters (optional)
- function body inside curly brackets or a single statement of function body in front of
=>.
Your question is about point #5. The difference between {} and => function body is that the curly brackets allow you to write multiple statements separated with a semi-colon ; while the second approach shall just be one statement, ended with a single semi-colon ;.
Let's have a look at a few examples. Here is a simple log() function that allows you to log any Object instance to the debug console:
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
Note how the function has a return type of void (point 1), a name called log (point 2), no parameters denoted by () (point 3 & 4) and a function body which is a single statement with => (point 5).
You could write the same function with curly brackets (point 5) instead of => like so:
extension Log on Object {
void log() {
devtools.log(toString());
}
}
The result of which will be exactly the same as the previous implementation.
Now let's look at another example where your function has a return value and some parameters.
String fullName(String firstName, String lastName) {
return "$firstName $lastName";
}
Since this function has simply one statement, the return statement and just one semi-colon, it could be re-written as an arrow function like so;
String fullName(
String firstName,
String lastName,
) =>
"$firstName $lastName";
So I would say the unwritten rules are:
Use arrow-functions if the body of your function is simple to understand. You could even have multiple lines of code inside an arrow-function's body as long as it's understandable, it's OK to use.
Use function bodies with curly-brackets if your function's body is rather complicated, consisting of multiple perhaps un-related pieces of code.
onTap: press()you are calling thepressfunction and passing the return value toonTap. WithonTap: () => press()you are creating an anonymous function, and passing the function toonTap. What you should most likely be doing is neither. Instead doonTap: presswithout the parenthesis(). This will pass thepressfunction rather than the result of calling thepressfunction.press()topress.pressfromFunctiontovoid Function(). See also dart.dev/guides/language/effective-dart/…