Issue
I have met a problem which is "Exception has occurred.
FlutterError (setState() or markNeedsBuild() called during build.".
I solve the problem with the following code:
@override
Widget build(BuildContext context) {
return GestureDetector(
//onTap: press(), error
onTap: () => press()
But I don’t know why.
So, I want to know What is the difference between function() and ()=> function() in flutter?
Solution
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.
Answered By – Vandad Nahavandipoor
Answer Checked By – Willingham (BugsFixing Volunteer)