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

() => expression or () { statements } creates a closure or inline function.

This way you create inline a function that is passed as argument to be called in case of the event onPressed by the widget you pass it to.

The expression or statements have the context where they were created available and can access and use all members and identifiers available in that context (variables, methods, functions, typedefs, …).

If you use

  • onPressed: myFunction a reference to an existing function is passed.
    This only works if the parameters of the callback expected by onPressed and myFunction are compatible.
  • onPressed: myFunction() myFunction() is executed and the returned result is passed to onPressed. This is a common mistake when done unintentionally when actually the intention was to pass a reference to myFunction instead of calling it.

Leave a Comment