Flutter/Dart - Difference between () {} and () => {}

They are both for expressing anonymous functions. The fat arrow is for returning a single line, braces are for returning a code block.

A fat arrow trying to return a code block will not compile.


The fat arrow syntax is simply a short hand for returning an expression and is similar to (){ return expression; }.
According to the docs.

Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression

void main(){
    final cls = TestClass();
    cls.displayAnInt((){
       //you can create statements here and then return a value
       int num1 = 55;
       int num2 = 1;
       int sum = num1 + num2;
       return sum;
    });
   cls.displayAnInt(() => 55 + 1); // simply return an int expression
}
class TestClass{

    displayAnInt(makeIntFunc){

       int intValue = makeIntFunc();
       print('The int value is $intValue');
    }
}

From the code above, You can see that multiline statement can be made when the callback function is used and then a value is returned, while the fat arrow simply has an expression with no return keyword.

Considering your answer about fat arrows not supporting multiline statements in dart. This is quite understandable since doing () => {somtheing} would imply you are returning a map and it would expect to see something like () => {'name':'John', 'age':25} and not () => { _myTxt = "Text Changed";_myTxt = "Never Mind"; } .


I found that the mean the exact same thing. The only difference is that you can use (you don't have to) the fat arrow if there is only one statement. Following is the above RaisedButton declaration with the fat arrow. Notice I had to remove two curly braces and one semi-colon:

RaisedButton(
  onPressed: () {
    setState(() =>
      _myTxt = "Text Changed"
    );
  },

If you are used to other languages that allow you to put multiple statements after a fat arrow you'll you'll find that you can't in dart and if you try you'll get an error as in the following:

this wont work

RaisedButton(
  onPressed: () {
    setState(() => {
      _myTxt = "Text Changed";
      _myTxt = "Never Mind";
    });
  },

=> is used to return a value of an anonymous function.

() {} lets you execute multiple statements.

while

() => {myVar} or () => myVar; allows one single statement.

() => myVar; is short and simple when returning one statement.


The same logic goes for creating non anonymous functions too.

Single statement func func() => y = x + x;

Multiple statement func

func () {
   x = x + x; 
   print(x + ' value of x');
};

Tags:

Dart

Flutter