What does the empty parentheses after the onPressed property mean in Dart?

前端 未结 5 1401
情歌与酒
情歌与酒 2020-12-03 15:11

I know the syntax for calling a function after onPressed and onTap for a widget. There are two options We can use either the () => functio

5条回答
  •  一个人的身影
    2020-12-03 15:56

    They are not the same thing. According the the language docs, the fat arrow is syntactical sugar for a return statement.

    https://www.dartlang.org/guides/language/language-tour#functions

    () => function()
    

    is comparable to this line

    (){ return function(); }
    

    not this statement

    () { function(); } //returns void
    

    I guess you got away with it because both handlers have a tendency to be void.

    https://docs.flutter.io/flutter/dart-ui/VoidCallback.html

    https://docs.flutter.io/flutter/gestures/GestureTapCallback.html

    https://docs.flutter.io/flutter/material/ListTile/onTap.html

    https://docs.flutter.io/flutter/material/IconButton/onPressed.html

    void main() {
      num add(a,b) => a + b;
      num add_void(a,b) { a+b; }
      for (int i = 0; i < 5; i++) {
        print('hello ${i + 1}');
        print(add(i,i));
        print(add_void(i,i));
      }
    }
    

提交回复
热议问题