Flutter app development has been a revolution for developers across the globe. And the magic of it lies in its widgets. This article will uncover the mystery around one such widget, WillPopScope, used extensively in Flutter.
In a world full of apps, customization is what makes yours unique. Our beloved Flutter app shines here due to its high diversity of widgets. One such class is the WillPopScope widget, which allows us to control the screen navigation of our Flutter app in a user-friendly way. So, let's dive into the Flutter WillPopScope class to unwrap the magic behind this class and see how you can leverage it to design your favorite app.
In the simplest terms, WillPopScope is a widget class in Flutter that registers to attempt to veto by the user to dismiss the enclosing ModalRoute. Hence, it's a helpful widget for controlling how a Flutter app responds to screen-exit attempts, commonly with the back button press event. You can intercept the actions and provide extra functionality, such as pop-up dialogs, or even cancel the action entirely.
The most significant properties of the WillPopScope widget are child and onWillPop. The child property accepts a single child widget that sits below it in the tree, while onWillPop expects a callback function that handles the back button press event.
In Flutter, the WillPopScope class is generally used in scenarios where we need confirmation from the user before exiting a screen or application. For instance, when you want to show a confirmation dialog to the user before they proceed back to the previous screen, or when developing an app like Twitter and you want to confirm whether the user has completed their tweet before exiting the current screen, WillPopScope is an excellent tool to use.
Now that we have covered the basics let's look at how to implement WillPopScope in Flutter.
The first thing we need is to set up our main class. For this example, we will use a stateless widget named MyApp. The code will look something like this:
1void main() { 2 runApp(MyApp()); 3} 4 5class MyApp extends StatelessWidget { 6 @override 7 Widget build(BuildContext context) { 8 return MaterialApp( 9 title: 'Flutter WillPopScope Demo', 10 theme: ThemeData( 11 primarySwatch: Colors.blue, 12 ), 13 home: MyHomePage(title: 'Flutter WillPopScope Home Page'), 14 ); 15 } 16}
As you can see, we have the entry point void main, which runs our application. The class MyApp extends the StatelessWidget and returns a MaterialApp widget with MyHomePage as the home widget.
With our main class set up, it's time to implement the WillPopScope widget. First, we'll create a StatefulWidget named MyHomePage. We will initialize it later as the child of our WillPopScope widget.
1class MyHomePage extends StatefulWidget { 2 MyHomePage({Key? key, required this.title}) : super(key: key); 3 final String title; 4 5 @override 6 _MyHomePageState createState() => _MyHomePageState(); 7}
Now, let's focus on the real hero - WillPopScope. Here's how to encompass MyHomePage inside the WillPopScope widget:
1class _MyHomePageState extends State<MyHomePage> { 2 DateTime? _lastClicked; // tracking the last time the back button was clicked 3 4 @override 5 Widget build(BuildContext context) { 6 return WillPopScope( 7 onWillPop: () async { 8 if (_lastClicked == null || 9 DateTime.now().difference(_lastClicked!) > Duration(seconds: 1)) { 10 _lastClicked = DateTime.now(); 11 return false; 12 } else { 13 return true; 14 } 15 }, 16 child: Scaffold( 17 appBar: AppBar( 18 title: Text(widget.title), 19 ), 20 body: Center( 21 child: Text('Flutter WillPopScope Demo'), 22 ), 23 ), 24 ); 25 } 26}
The WillPopScope widget wraps around our Scaffold widget in the above build method. We have two parameters: onWillPop and child. The child property accepts the Scaffold widget, and onWillPop, the essential part, receives a callback.
The callback function of onWillPop is executed when the user tries to get back to the previous screen, or in simple words, they press the back button. This function returns a Future<bool>
to control that back button press event. When false is returned, the app will stay on the current page and vice versa.
This sample app demonstrates Flutter WillPopScope's usefulness by handling accidental back button presses. You may have noticed it if you have used one of the thousands of other apps implementing this effective feature.
As developers, we all know that as important as understanding the mechanism of any widget, what boosts our skills is exploring and understanding a real Flutter example. So, let's create a simple application demonstrating the WillPopScope's use.
In this example, when a user wants to exit the app or return to the previous screen (an important user action referred to as a back button press event), we will display a dialog box to confirm their action.
To simplify it, the example will contain two pages, the HomePage (that we have already created) representing our initial view, and a NextPage to navigate to with a simple button. Let's create NextPage as follows:
1class NextPage extends StatelessWidget { 2 @override 3 Widget build(BuildContext context) { 4 return Scaffold( 5 appBar: AppBar( 6 title: Text('Next Page'), 7 ), 8 body: Center( 9 child: ElevatedButton( 10 child: Text('Go Back'), 11 onPressed: () { 12 Navigator.pop(context); 13 }, 14 ), 15 ), 16 ); 17 } 18}
NextPage is a simple StatelessWidget displaying a button to navigate back to the previous screen.
Next, let's modify the _MyHomePageState a bit:
1class _MyHomePageState extends State<MyHomePage> { 2 DateTime? _lastClicked; 3 4 @override 5 Widget build(BuildContext context) { 6 return WillPopScope( 7 onWillPop: () async { 8 final now = DateTime.now(); 9 bool allowPop = false; 10 if (_lastClicked == null || now.difference(_lastClicked!) > Duration(seconds: 1)) { 11 _lastClicked = now; 12 ScaffoldMessenger.of(context).showSnackBar( 13 SnackBar( 14 content: Text('Double click back button to exit'), 15 duration: Duration(seconds: 1), 16 ), 17 ); 18 } else { 19 allowPop = true; 20 } 21 return Future<bool>.value(allowPop); 22 }, 23 child: Scaffold( 24 appBar: AppBar( 25 title: Text(widget.title), 26 ), 27 body: Center( 28 child: ElevatedButton( 29 child: Text('Go to Next Page'), 30 onPressed: () { 31 Navigator.push( 32 context, 33 MaterialPageRoute( 34 builder: (context) => NextPage(), 35 ), 36 ); 37 }, 38 ), 39 ), 40 ), 41 ); 42 } 43}
In this updated _MyHomePageState class, we added an ElevatedButton to our Home Page. When this button is clicked, it will navigate us to the next page, i.e., the NextPage we just created.
In the onWillPop callback function, we incorporated a double-click-to-exit feature. Here's how it works:
Creating a user-friendly and intriguing atmosphere in your Flutter app is a fundamental need in today's development world. With the WillPopScope class in Flutter, you can now intercept button press events, especially the back button press event, and customize your app's navigation paths to boost your user experience and stand out from other apps.
WillPopScope in Flutter lets you handle the scope of user pops or accidental backpresses, making your Flutter app more interactive and precise. Whether your users want to navigate back to the previous screen or exit the app entirely, you can guide and enhance their experience following their selection and needs.
No matter what your flutter app is about, using WillPopScope will undoubtedly provide an extra edge to your app performance.
We hope you enjoyed this deep dive into the powerful WillPopScope class in Flutter! Here, we only scratched the surface. As you practice and build various app features, we are sure you will discover more exciting things you can do with WillPopScope. So, let's keep fluttering and creating fantastic apps!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.