Most of the apps implement back button press to app exit confirmation popup into their app. In flutter, it's really easy. If you want to add an app exit prompt into your flutter application then this step by step tutorial will help you to add an app exit dialog into your app when the user will press the back button from the home screen.
First, make a dart file exit-popup.dart
into lib/widgets
directory. We are going to make it a reusable widget so that we can easily use it in any future application easily.
import 'dart:io';
import 'package:flutter/material.dart';
Future<bool> showExitPopup(context) async{
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
height: 90,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Do you want to exit?"),
SizedBox(height: 20),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
print('yes selected');
exit(0);
},
child: Text("Yes"),
style: ElevatedButton.styleFrom(
primary: Colors.red.shade800),
),
),
SizedBox(width: 15),
Expanded(
child: ElevatedButton(
onPressed: () {
print('no selected');
Navigator.of(context).pop();
},
child: Text("No", style: TextStyle(color: Colors.black)),
style: ElevatedButton.styleFrom(
primary: Colors.white,
),
))
],
)
],
),
),
);
});
}
Info We have designed the app exit popup in step-1. Now we can use it in our app easily. To do that, we have to just call the showExitPop
function via WillPopScope
widget.
Action Open your home screen dart file and wrap the Scaffold
with WillPopScope
widget. WillPopScope
widget required 2 params, One is a child
which contains our Scaffold and the other one is onWillPop
.
import 'package:flutter/material.dart';
import 'package:flutter_tutorial/widgets/exit-popup.dart';
class HomePage extends StatefulWidget {
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => showExitPopup(context),
child: Scaffold(
appBar: AppBar(title: Text("Flutter Tutorial"),),
body: Center(
child: Text("Welcome"),
)
),
);
}
}
After doing that, our app user will get an app exit popup when they press the back button from the app home page. Hope this tutorial will help you to learn how to make an app exit popup in the Flutter application. If you find it useful then please share it with others.