In some pages APP in order to prevent user error, click on the back button to exit leading to APP, can be set to click twice within a certain period of time which allowed the return key to exit the APP, this function can be completed by WillPopScope and SystemNavigator.pop achieve
We first look at the results:
To achieve that we need to be wrapped in an outer WillPopScope used to monitor the user clicks the back button
Widget build(BuildContext context) { return WillPopScope( child: Scaffold( body: Center( child: Text ( 'click twice to return to exit the APP'), ), ), onWillPop () { // Return to key operations }, ); }
After wrapped WillPopScope you will find that you click back key no effects
Then we need to make a judgment of time, such as two clicks within two seconds (time can be the difference between the two time difference by comparison) to exit the operation can be carried out
DateTime lastPopTime; @override Widget build(BuildContext context) { return WillPopScope( child: Scaffold( body: Center( child: Text ( 'click twice to return to exit the APP'), ), ), onWillPop () { // Return to key operations if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){ lastPopTime = DateTime.now(); Toast.toast (context, msg: 'press to exit'); }else{ lastPopTime = DateTime.now(); // exit the app } }, ); }
Finally, we then Finish to exit through the implementation of SystemNavigator.pop, need references
import 'package:flutter/services.dart';
The final code
DateTime lastPopTime; @override Widget build(BuildContext context) { return WillPopScope( child: Scaffold( appBar: AppBar( title: Text ( 'click twice to return to exit the APP', style: TextStyle (color: Colors.white, fontSize: 20),), ), body: Center( child: Text ( 'click twice to return to exit the APP'), ), ), onWillPop: () async{ // Return to key operations if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){ lastPopTime = DateTime.now(); Toast.toast (context, msg: 'press to exit'); }else{ lastPopTime = DateTime.now(); // exit the app await SystemChannels.platform.invokeMethod('SystemNavigator.pop'); } }, ); }
This can be achieved to friends ~
Toast.toast (); This message box may look https://www.cnblogs.com/gxsyj/p/11018117.html