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

前端 未结 6 2096
孤独总比滥情好
孤独总比滥情好 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: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/

提交回复
热议问题