Jagadeesh
Jagadeesh

Reputation: 307

When I Click on Device Back Button app is closed

When I click on the app bar back button it goes to the previous page. But when click on the device back button app is closed. Please tell me what will happen.

@override
  Widget build(BuildContext context) {
    return ScopedModelDescendant(
      builder: (BuildContext context, Widget child, MainModel model) {
        return WillPopScope(
          onWillPop: ()async{
            return true;
          },
          child: Scaffold(
          appBar: AppBar(
            title: Text('Add User Info'),
          ),
          body: Container(
            padding: EdgeInsets.all(10.0),
            child: _buildOrderForm(model),
          ),
        ),
        );
      },
    );
  }

Upvotes: 1

Views: 286

Answers (2)

deepak dumraliya
deepak dumraliya

Reputation: 11

Method of the widget WillPopScope must be used as root

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      onWillPop: _onBackPressed,
      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"),
        ),
      ),
    );
  }

In the above snippet, we have written a _onBackPressed method. It'll invoke when you back press from the mobile hardware button.

Upvotes: 1

gi097
gi097

Reputation: 7721

You are already using WillPopScope which is good! However I see one thing that you have not properly implemented, which is:

onWillPop: ()async{
    return true;
},

You need to return a Future of false to disable the route being popped. See more info here:

https://api.flutter.dev/flutter/widgets/WillPopScope/onWillPop.html

If the callback returns a Future that resolves to false, the enclosing route will not be popped.

This should work:

onWillPop: () => Future<bool>.value(false),

Upvotes: 1

Related Questions