6

In my Application when i click on back button of device it is closing app. I used Willpopscope but it is not working. But when i create a sample project it is working. Can Any one explain me why it is not working in existing application. I shared my code. (In Appbar back arrow working fine but issue is with device back button)

    Future<bool> _onWillPop() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
                title: new Text('Are you sure?'),
                content: new Text('Unsaved data will be lost.'),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: new Text('No'),
                  ),
                  new FlatButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: new Text('Yes'),
                  ),
                ],
              ),
        ) ??
        false;
  }

@override
  Widget build(BuildContext context) {
    return new WillPopScope(
      onWillPop: _onWillPop,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "On Back pressed", 
            style: new TextStyle(color: Colors.white),
          ),
        ),
        body: new Center(
          child: new Text("Home Page"),
        ),
      ),
    );
  }
Jagadeesh
  • 277
  • 1
  • 4
  • 11

2 Answers2

1

replace your _onWillPop method with this _onWillPop()async{ return false; }

Murat Aslan
  • 1,446
  • 9
  • 21
  • I'm trying this, it is not working when I click the back button app closed. – Jagadeesh Jun 14 '19 at 04:28
  • D/ZrHung.AppEyeUiProbe(11690): stop checker. D/ZrHung.AppEyeUiProbe(11690): Current Activity:false D/ZrHung.AppEyeUiProbe(11690): not watching, wait. W/libEGL (11690): EGLNativeWindowType 0x74e4b8b010 disconnect failed I/SurfaceView(11690): delay destroy surface control W/libEGL (11690): EGLNativeWindowType 0x74e4b69010 disconnect failed I/SurfaceView(11690): need destroy surface control D/ViewRootImpl[MainActivity](11690): surface should not be released – Jagadeesh Jun 14 '19 at 04:30
1

WillPopScope#onWillPop doesn't allow the pop to occur if it returns a false value. You can try something like this if you don't want to show an AlertDialog.

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      onWillPop: () => Future.value(false),
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "On Back pressed",
            style: new TextStyle(color: Colors.white),
          ),
        ),
        body: new Center(
          child: new Text("Home Page"),
        ),
      ),
    );
  }
Shababb Karim
  • 3,614
  • 1
  • 22
  • 35