Search code examples
androidiosflutterdart

How to override the back button on a "showDialog" in Flutter?


I am trying to show a dialog Box when users try to log out and I want to override the back button if the user tries to press back while the dialog box is present on screen. For that I tried to use WillPopScope but somewhere I am doing things wrong. It is throwing me an error:

enter image description here

Logging out code :

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

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        print("pressed back button");
        return false;
      },
      child: _showLoaderDialog(context),
    );
  }

  _showLoaderDialog(BuildContext context){
    AlertDialog alert=AlertDialog(
      content: new Row(
        children: [
          CircularProgressIndicator(),
          Container(margin: EdgeInsets.only(left: 7),child:Text("Logging out..." )),
        ],),
    );
    showDialog(barrierDismissible: false,
      context:context,
      builder:(BuildContext context){
        return alert;
      },
    );

  }
}

Why this error is showing up? Another question which I want to ask that where can I write the logging out logic code which when completes pop the dialog box and route to login page screen?


Solution

  • I'm not sure if understand what do you want exactly, but if you want to cancel the back button effect while the dialog box in the screen you can wrap it in WillPopScope too like this :

    class HomePage  extends StatelessWidget {
    
    @override
    Widget build(BuildContext context) {
    
    Future<bool> exitConfirm() async {
      
      return await showDialog(
        barrierDismissible : false,
        context: context,
        builder: (context) => WillPopScope(
            onWillPop: () async => false,
          child: AlertDialog(
            content:  Row(
              children: [
                CircularProgressIndicator(),
                Container(margin: EdgeInsets.only(left: 7),child:Text("Logging out..." )),
              ],),
    
          ),
        ),
      )??false;
    }
    
    
    return WillPopScope(
      onWillPop:exitConfirm,
      child: Scaffold  (
    
          appBar: AppBar(),
        body: const Center(
          child: Text('Test page'),
        )
      ),
    );
    
     }
    
     }
    

    The result:

    enter image description here

    notice that I have added this line to the showDialog so when you click on the screen the dialog doesn't dismiss :

    barrierDismissible : false,