Search code examples
flutterflutter-alertdialog

Flutter: Alert Dialog with CupertinoNavigationBar back button


Flutter Question: I am trying to implement an alert dialog on my Cupertino Navigation bar back button when pressed, but I think I have no idea how this would work when I'm not using a custom back button.

Does anyone have an idea?

class ameriCares extends StatelessWidget {
const ameriCares({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
  navigationBar: CupertinoNavigationBar(middle: Text("Americares")),  //i want to add the alert dialog here on the back button
  child: SafeArea(
    child: WebView(
      initialUrl: AppLocalizations.of(context)!.americares,
      javascriptMode: JavascriptMode.unrestricted,
    ),
    //bottomNavigationBar: CustomBottomNavBar(selectedMenu: MenuState.give),
  ),
);
}
}

Thanks a million


Solution

  • Try adding a leading parameter to the CupertinoNavigationBar - GestureDetector with an icon.

    Widget build(BuildContext context) {
      return CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text(
            "Americares",
          ),
          leading: GestureDetector(
            onTap: () {
              showDialog<void>(
                context: context,
                barrierDismissible: false, // user must tap button!
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: const Text('AlertDialog Title'),
                    content: SingleChildScrollView(
                      child: ListBody(
                        children: const <Widget>[
                          Text('This is a demo alert dialog.'),
                          Text('Would you like to approve of this message?'),
                        ],
                      ),
                    ),
                    actions: <Widget>[
                      TextButton(
                        child: const Text('Approve'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  );
                },
              );
            },
            child: Icon(
              CupertinoIcons.left_chevron,
              color: CupertinoColors.black,
            ),
          ),
        ), //i want to add the alert dialog here on the back button
        child: SafeArea(
          child: WebView(
            initialUrl: AppLocalizations.of(context)!.americares,
            javascriptMode: JavascriptMode.unrestricted,
          ),
          //bottomNavigationBar: CustomBottomNavBar(selectedMenu: MenuState.give),
        ),
      );
    }