Send call back method as parameter

Advertisements

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:

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.

Leave a ReplyCancel reply