How To Override the “Back” button in Flutter? [duplicate]
Asked Answered
V

1

174

On my Home widget, when user taps system back button, I want to show a confirmation dialog asking "Do you want to exit the App?"

I don't understand how I should override or handle the system back button.

Vezza answered 19/3, 2018 at 5:58 Comment(0)
K
364

You can use WillPopScope to achieve this.

Example:

import 'dart:async';

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) :super(key: key);

  final String title;

  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {

  Future<bool> _onWillPop() async {
    return (await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Are you sure?'),
        content: new Text('Do you want to exit an App'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text('No'),
          ),
          TextButton(
            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("Home Page"),
        ),
        body: new Center(
          child: new Text("Home Page"),
        ),
      ),
    );
  }
}

The ??-operator checks for null, see here. This is important because if you click outside the dialog, showDialog returns null and in this case false is returned.

Kaneshakang answered 19/3, 2018 at 6:22 Comment(10)
Can we change the icon too of the back button?Obit
Yes, of course. There is property leading that the AppBar takes. You can specify an IconButton with what every icon you want or any other widgets too.Kaneshakang
Thanks but I also figured that out by my own. We have limited space in leading property, so we can't really use any widget. It should be generally an IconButton that you wanna use.Obit
But this will not override the physical device back button? How to detect device back button?Ossify
Sorry, I think it does. You mean it only works with flutter back button? I see it works with hard and soft back buttons too.Kaneshakang
Can somebody please explain me what does the ?? false code at the very end of the _onWillPop method does?Hartal
@Hartal The varvalue ?? false instruction tells the compiler to return false if the varvalue is nullCastara
Why async await is used here ?Knowhow
on yes TextButton pressed, it should be SystemNavigator.pop(); instead of Navigator.of(context).pop(true)Joliejoliet
'WillPopScope' is deprecated and shouldn't be used.Charinile

© 2022 - 2024 — McMap. All rights reserved.