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

前端 未结 6 2109
孤独总比滥情好
孤独总比滥情好 2021-02-13 03:36

In Flutter/Dart the examples sometimes show fat arrow and sometimes dont. Here are examples:

RaisedButton(
  onPressed: () {
    setState(() {
      _myTxt = \"         


        
相关标签:
6条回答
  • 2021-02-13 04:16

    => 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');
    };
    
    0 讨论(0)
  • 2021-02-13 04:30

    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"; } .

    0 讨论(0)
  • 2021-02-13 04:33

    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.

    0 讨论(0)
  • 2021-02-13 04:35

    There seems to be one difference at least in case of Dart version 2.10:

    If the expression to be executed is a Future, then the execution order is not the same.

    =>

    new Future(() => print('future #1 of 2'))
      .then((_) => new Future(() => print('future #1a (a new future)')))
      .then((_) => print('future #1b'));
    
    new Future(() => print('future #2 of 2'))
      .then((_) => new Future(() => print('future #2a (aa new futue)' )))
      .then((_) => print('future #2b'));
    

    The result is:

    future #1 of 2
    future #2 of 2
    future #1a (a new future)
    future #1b
    future #2a (aa new futue)
    future #2b`
    

    {} :

    new Future(() => print('future #1 of 2'))
      .then((_) => new Future(() => print('future #1a (a new future)')))
      .then((_) => print('future #1b'));
    
    new Future(() => print('future #2 of 2'))
      .then((_) { new Future(() => print('future #2a (aa new futue)' )); })
      .then((_) => print('future #2b'));
    

    The result is

    future #1 of 2
    future #2 of 2
    future #2b
    future #1a (a new future)
    future #1b
    future #2a (a new futue)
    
    0 讨论(0)
  • 2021-02-13 04:36

    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";
        });
      },
    
    0 讨论(0)
  • 2021-02-13 04:37

    => Short hand expression is used to define a single expression in a function. Enough with the definition and properties.

    • By using fat arrow => the curly brackets needs to be removed. Otherwise, the code editor will show you an error.
    • If a function has a return type then by using a Fat arrow it is required to remove the return keyword.

    Below Both are the same function and will return the same value. Just a different syntax

    This is with => type

    var size = (int s) => s*2;
    

    This is return type

    var size = (int s) { 
      return s*2; 
    } 
    

    To understand the concept with a real code example. We will consider the same examples that are done in Dart functions tutorial. The code executes the Perimeter and Area of a rectangle. This is how usually it is done with the help of functions.

     void main() {
      findPerimeter(9, 6);
      var rectArea = findArea(10, 6);
      print('The area is $rectArea');
    }
    
    void findPerimeter(int length, int breadth) {
      var perimeter = 2 * (length * breadth);
      print('The perimeter is $perimeter');
    }
    
    int findArea(int length, int breadth) {
      return length * breadth;
    }
    

    The given functions can be optimized with the help of fat arrow in Dart.

     void main() {
      findPerimeter(9, 6);
      var rectArea = findArea(10, 6);
      print('The area is $rectArea');
    }
    
    void findPerimeter(int length, int breadth) =>
      print('The perimeter is ${2 * (length * breadth)}');
    
    
    int findArea(int length, int breadth) =>
       length * breadth;
    

    After hitting the run button we are still getting the same result.

    The perimeter is 108
    The area is 60
    

    Is from : https://flutterrdart.com/dart-fat-arrow-or-short-hand-syntax-tutorial/

    0 讨论(0)
提交回复
热议问题