简体   繁体   中英

Device back button not working in flutter

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM