Flutter Back Button to create an AlertDialog to close the application

From the Splash Screen post, there is one issue that user press back button, the screen goes back to splash screen and stays there forever.

In order to fix this issue, when user press back button, it will popup an AlertDialog box asking if user wants to close the app or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SplashScreen(),
);
}
}

class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
// TODO: implement initState
Timer(Duration(seconds: 3), () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(title: 'Splash Screen Test'),
),
);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.black,
child: Center(
child: CircleAvatar(
radius: 30.0,
backgroundColor: Colors.amberAccent,
foregroundColor: Colors.red,
child: Icon(
Icons.adb,
size: 50.0,
),
),
),
),
);
}
}

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

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
Future<bool> _onWillPop() {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Are you sure?'),
content: Text('Do you want to exit an App'),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('No'),
),
FlatButton(
onPressed: () => exit(0),
/*Navigator.of(context).pop(true)*/
child: Text('Yes'),
),
],
),
) ??
false;
}

@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Hello World',
),
],
),
),
),
);
}
}

If you write the code above, the screen doesn’t go back to Splash screen and exit the app at the current screen.

Share