Home > Back-end >  How to dismiss an AlertDialog in Flutter?
How to dismiss an AlertDialog in Flutter?

Time:10-14

I have a utility class that shows an alert dialog to which I'm passing a VoidCallback which usually contains Navigator.of(context).pop() to dismiss the alert dialog. However it throws a _CastError (Null check operator used on a null value) on button press.

class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required VoidCallback onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: onPress,
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

If I explicitly pass Navigator.pop(context,true) to the onPress method it works just fine, however I need this to be a reusable static method with different onPress functionalities that does more than just pop the dialog.

class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required VoidCallback onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: () {
            return Navigator.pop(context, true);
          },
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

Your Parent Context does not contain the CustomAlertDialog. You should pass the context provide by the builder into the onPress function and call navigator.pop with the context provided in the builder function in showDialog.

class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required void Function(BuildContext context) onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: (){ onPress(context) },
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

you can try this :

void show(BuildContext context, String title, {Function callback})

 onPressed: () {
          if (callback != null) {
                   Navigator.pop(context, true);
                   callback();
            } else {
                      Navigator.pop(context, true);

            }
         }, 
  • Related