Reputation: 6789
Code will explain all:
class ResultOverlay extends StatefulWidget {
final bool _isCorrect;
VoidCallback _onTap;
ResultOverlay(this._isCorrect, this._onTap);
......
......
}
Its state class:
class ResultOverlayState extends State<ResultOverlay>{
@override
Widget build(BuildContext context) {
........
child: new InkWell(
onTap: () => widget._onTap,
.....
.....
}
Passing of callback function:
new ResultOverlay(isCorrect, () {
() => CallAnswerPage();
})
What I am missing here?
Upvotes: 48
Views: 96052
Reputation: 512676
This is a more general answer for future viewers.
There are a few different types of predefined callbacks:
final VoidCallback myVoidCallback = () {};
final ValueGetter<int> myValueGetter = () => 42;
final ValueSetter<int> myValueSetter = (value) {};
final ValueChanged<int> myValueChanged = (value) {};
Notes:
ValueSetter
, but its name emphasizes that the given value actually changed (and was not just set with the same value again).See this answer for more details.
When you are asked to provide a callback to an API, you can directly write the callback:
onPressed: () {},
Or you can supply the callback variable name (without parentheses):
onPressed: myVoidCallback,
It would be unnecessarily verbose to use both forms (but you could if you included the parentheses after the variable name):
onPressed: () {
myVoidCallback();
},
This one is equivalent (but also unnecessarily verbose):
onPressed: () => myVoidCallback(),
Just use one of the "Good" forms from above.
The exception would be if you wanted to do something like call a value setter when the parameter is only asking for a void callback:
onPressed: () => myValueSetter(42),
Upvotes: 74
Reputation: 272
As the name suggests,VoidCallback listens for click events.here is below example.
ResultOverlay(true, _requestPermission);
ResultOverlay(_isCorrect, () {
print('I am a voidCallback');
});
or
ResultOverlay(true, _requestPermission);
ResultOverlay(_isCorrect, myVoidCallback());
ResultOverlay
class ResultOverlay extends StatefulWidget {
final bool _isCorrect;
VoidCallback _onTap;
ResultOverlay(this._isCorrect, this._onTap);
@override
State<ResultOverlay> createState() => _ResultOverlayState();
}
class _ResultOverlayState extends State<ResultOverlay> {
@override
Widget build(BuildContext context) {
return Container(
child: InkWell(
onTap: widget._onTap,
),
);
}
}
Upvotes: 0
Reputation: 11
onTap: () => widget._onTap,
as ontap needs function '()=>' itself is a function, So it will be onTap:widget._onTap,
and if you want to use in stateless widget ontap:_ontap
Upvotes: 1
Reputation: 6789
I was not passing the callback correctly. Here is the correct syntax:
new ResultOverlay(
isCorrect,
() => callAnswerPage()
)
So silly mistake :)
Upvotes: 30
Reputation: 277677
Everything is fine beside how you use it.
Change
onTap: () => widget._onTap,
to
onTap: widget._onTap,
inside your State
class
Upvotes: 10