I'm pretty inexperienced with Flutter, I created a widget with this piece of code inside:
With code written like this: (the ToolModify function is not called)
final VoidCallback ToolModify;
onTap: () {
// rest of the code
widget.ToolModify;
},
Instead, it is called with code written like this:
onTap: widget.ToolModify,
Can anyone explain to me why this happens?
Since I need to write other lines of code besides widget.ToolModify; how can i call the ToolModify function inside OnTap: () {...} ??
Hope someone can help me. Thanks :)
It is perfectly legal and good style to code like this:
onTap: widget.ToolModify,
In this case, widget.ToolModify
denotes a function and you assign the function to onTap
to make onTap
call the function later on.
If you call it like this, you make a new anonymous and parameterless function () {}
that just calls the other function widget.ToolModify()
:
onTap: () {
widget.ToolModify();
},
Note, that widget.ToolModify
denotes the function itself. While widget.ToolModify()
calls the function with no parameters.
Moreover, you may write this, since you return just one expression:
onTap: () => widget.ToolModify(),
Example
Have a look at this example that defines a function ad(), that returns an anonymous function and later on applies it to some arguments:
// This function takes one argument x and returns a new function
// of one parameter
Function(int) add( y ) {
return ( x ) => ( x + y );
}
// The above => notation is only applicable, if exactly one expression is returned
// In case the structure of the inner function is more complex, write
// it using non shorthand notation like so
Function(int) divideBy( y ) {
return ( x ) {
assert( y > 0 );
return ( x / y );
};
}
// Use the above function to create two specialist functions
Function(int) add100 = add( 100 );
// Simmilar, but implicitly typed
var add10 = add( 10 );
var halfOf = divideBy( 2 );
var doubleOf = divideBy( 0.2 );
// Now apply two specialized functions
print( add10( 1 ) );
print( add100( 1) );
print( halfOf( 10 ) );
print( doubleOf( 10 ) );
Outputs this:
11
101
5
50