Search code examples
androidiosflutterbackonbackpressed

Call onBackpress programatically in Flutter


How could I perform to call the backpress function (onWillPop) programatically on Flutter.

In Android Native what I need to do is call this when I need to simulate a backpress click.

this.onBackPressed();

My onBackPress function, It is set to onWillPop inside WillPopScope:

Future<bool> _onBackPressed() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
                title: Text("Você tem certeza?"),
                content: Text('Você realmente quer sair do app'),
                actions: <Widget>[
                  new RaisedButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: Text("Não")
                  ),
                  new RaisedButton(
                    onPressed: _signOut,
                    child: Text("Sim")
                  ),
                ],
              ),
        ) ??
        false;
  }

It shows a dialog and if yes is clicked the app log out.

My ideia is to create an back arrow on AppBar to do the same


Solution

  • If you want to call onWillPop just call the following method on Navigator instead of pop method. It will cause flutter to call onWillPop.

    Navigator.of(context).maybePop();