Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass callback in Flutter

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?

like image 657
pallav bohara Avatar asked May 31 '18 13:05

pallav bohara


People also ask

What is callback in Dart?

Dart allows callback functions but also provides the Future and Completer pair of types that work together to provide a future value that can be passed around your app. Only when the async call completes does the future value get a real value.


2 Answers

This is a more general answer for future viewers.

Callback types

There are a few different types of predefined callbacks:

final VoidCallback myVoidCallback = () {}; final ValueGetter<int> myValueGetter = () => 42; final ValueSetter<int> myValueSetter = (value) {}; 

Notes:

  • VoidCallback is an anonymous function that takes no arguments and returns no value.
  • ValueGetter is an anonymous function that returns a value, which you provide for someone who wants to get it.
  • ValueSetter is an anonymous function that takes a value as an argument, which you can use to set some other value.

See this answer for more details.

Ways to write the callback

Good

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, 

Less good

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.

Still good

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), 
like image 84
Suragch Avatar answered Oct 14 '22 17:10

Suragch


I was not passing the callback correctly. Here is the correct syntax:

new ResultOverlay(     isCorrect,      () => callAnswerPage() ) 

So silly mistake :)

like image 36
pallav bohara Avatar answered Oct 14 '22 18:10

pallav bohara