[FIXED] Wie schließe ich einen AlertDialog in Flutter?

Ausgabe

Ich habe eine Dienstprogrammklasse, die einen Warndialog anzeigt, an den ich eine übergebe VoidCallback, die normalerweise enthält Navigator.of(context).pop(), um den Warndialog zu schließen. Allerdings wirft es einen _CastError (Null check operator used on a null value)auf Knopfdruck.

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",
          ),
        ),
      ),
    );
  }
}

Wenn ich explizit Navigator.pop(context,true)an die onPressMethode übergebe, funktioniert es einwandfrei, aber ich brauche dies, um eine wiederverwendbare statische Methode mit verschiedenen onPressFunktionalitäten zu sein, die mehr als nur den Dialog öffnet.

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",
          ),
        ),
      ),
    );
  }
}

Lösung

Ihr übergeordneter Kontext enthält den CustomAlertDialog nicht. Sie sollten den vom Builder bereitgestellten Kontext an die onPress-Funktion übergeben und navigator.pop mit dem in der Builder-Funktion bereitgestellten Kontext in showDialog aufrufen.

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",
          ),
        ),
      ),
    );
  }
}


Beantwortet von –
GG.


Antwort geprüft von –
Jay B. (FixError Admin)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like