Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send call back method as parameter

I have a Dart class where I have a helper method for displaying an Alert. The alert is shown many times on the app, but the onPressed() on the alert does different things in different places. I want to send as a parameter, what I want the onPressed() to do.

Here is my helper method:

basicAlertWithOkWithCallback(String message, BuildContext context, void Function() f){

  showDialog(
    context: context,
    builder: (context) =>
        AlertDialog(
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () async {
                f;
              },
            ),
          ],
        ),
  );
}

I call the method from another screen like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

basicAlertWithOkWithCallback(‘Session sucessfully saved.’, context, callBack(context));

And on that screen I made this method, which I want to execute when OK is pressed:

callBack(BuildContext context){
  print('CALLED');
  Navigator.of(context).pop();
  Navigator.of(context).pop();
  Navigator.of(context).pop();
}

The problem is, this method gets called straight away when the alert is displayed, even before the user presses on OK. Why is it called right away, and not on the onPressed()

>Solution :

The reason why callBack method is called immediately when basicAlertWithOkWithCallback is called is because you are invoking the callBack method and passing its return value as a parameter to basicAlertWithOkWithCallback method, instead of passing the callBack method itself.

To fix this, you need to pass the callBack method as a parameter to basicAlertWithOkWithCallback method like this:

basicAlertWithOkWithCallback('Session successfully saved.', context, callBack);

Notice that we are not invoking the callBack method with () in the above code. Instead, we are passing a reference to the callBack method, so that it can be invoked later when the user presses the ‘OK’ button.

Also, you need to invoke the f function inside the onPressed callback by adding () after the f parameter like this:

onPressed: () async 
{
  f();
},

By doing this, the callBack method will only be called when the user presses the ‘OK’ button.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading