Handling back button and providing a different functionality is always a requirement among mobile developers. Flutter also helps you to do that. Let’s see how that works.
Watch Video Tutorial
This is achieved with the help of a widget called “WillPopScope”. ‘WillPopScope‘ has a method call ‘onWillPop‘ which can be used to override the back button functionality and its very easy to use. It should return a boolean true or false. True for the default behavior.
Here is a simple example that shows an alert dialog when user presses the back button. The AlertDialog will have a ‘YES’ and a ‘NO’ button. Clicking on yes will pop the current screen. Here there is only one screen, so popping the screen will close the application in Android.
Code goes like this…
import 'package:flutter/material.dart'; class Tip5 extends StatefulWidget { Tip5() : super(); final String title = "Back Button Demo"; @override Tip5State createState() => Tip5State(); } class Tip5State extends State<Tip5> { // Future<bool> _onBackPressed() { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Are you sure?'), content: Text('You are going to exit the application!!'), actions: <Widget>[ FlatButton( child: Text('NO'), onPressed: () { Navigator.of(context).pop(false); }, ), FlatButton( child: Text('YES'), onPressed: () { Navigator.of(context).pop(true); }, ), ], ); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: WillPopScope( onWillPop: _onBackPressed, child: Container(), ), ); } }
The ‘Future
Complete Source Code
Source Code is available in this link.