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

前端 未结 6 2148
挽巷
挽巷 2021-02-13 03:44

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

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


        
6条回答
  •  孤独总比滥情好
    2021-02-13 04:40

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

提交回复
热议问题