In this guide, we are going to show you the way to override the back button press and show exit confirmation dialogue. While you press the back button, Flutter generally pops the routes, and to listening such pops, there is a widget called WillPopScope(). See the example below to know the way to use WillPopScope() widget and listen to the back button press to override it.
Read this also: How to Make Double Press Back Button to Exit on Flutter App
WillPopScope(
onWillPop: false,
child:Scaffold( )
)
Wrap the Scaffold() widget with WillPopScope(), and pass the boolean value to onWillPop property. If you pass true, the back button press will dismiss your route, and if you pass false, the back button will not have any use.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Test App",
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
Future<bool> showExitPopup() async {
return await showDialog( //show confirm dialogue
//the return value will be from "Yes" or "No" options
context: context,
builder: (context) => AlertDialog(
title: Text('Exit App'),
content: Text('Do you want to exit an App?'),
actions:[
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
//return false when click on "NO"
child:Text('No'),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
//return true when click on "Yes"
child:Text('Yes'),
),
],
),
)??false; //if showDialouge had returned null, then return false
}
return WillPopScope(
onWillPop: showExitPopup, //call function on back button press
child:Scaffold(
appBar: AppBar(
title: Text("Override Back Button"),
backgroundColor: Colors.redAccent,
),
body: Center(
child: Text("Override Back Buttton"),
)
)
);
}
}
In this way, you can override the back button press on device, or listen back button press and show exit confirmation dialogue.
Please Wait...
No any Comments on this Article