To prevent users from accidentally exiting the app by pressing the back button, many apps intercept the back button click and implement some validation to avoid misclicks. For example, they may only consider the user wants to exit if the back button is clicked twice within a certain time frame. In Flutter, this can be achieved using WillPopScope
. Let's look at the default constructor for WillPopScope
:
const WillPopScope({ ... required WillPopCallback onWillPop, required Widget child })
onWillPop
is a callback function that is called when the user clicks the back button (including the navigation back button and the Android physical back button). This callback must return a Future
object; if the returned future resolves to false
, the current route will not be popped (will not exit); if it resolves to true
, the current route will be popped and exited. We need to provide this callback to determine whether to exit.
Example
To prevent users from accidentally exiting the app by pressing the back button, we intercept the back button event. If the user presses the back button twice within 1 second, then the app will exit; if the interval exceeds 1 second, it will not exit, and the timer will reset. The code is as follows:
import 'package:flutter/material.dart'; class WillPopScopeTestRoute extends StatefulWidget { @override WillPopScopeTestRouteState createState() { return WillPopScopeTestRouteState(); } } class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> { DateTime? _lastPressedAt; // Last click time @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) { // Reset timer if clicks are more than 1 second apart _lastPressedAt = DateTime.now(); return false; } return true; }, child: Container( alignment: Alignment.center, child: Text("Press back button twice within 1 second to exit"), ), ); } }
Readers can run the example to see the effect.