Flutter组件学习(22)导航返回拦截(WillPopScope)

简介

Flutter中可以通过WillPopScope来实现返回按钮拦截

onWillPop是一个WillPopScope的回调函数,当用户点击返回按钮时被调用

WillPopScope必须包含child,否则会报错

实现双击返退出APP

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';void main() {runApp(MyApp());
}class MyApp extends StatefulWidget {@overrideState<StatefulWidget> createState() {return WillPopTest();}
}class WillPopTest extends State {DateTime _lastTime;@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(backgroundColor: Colors.blue,centerTitle: true,title: Text('实现二次点击退出',style: TextStyle(fontSize: 18, color: Colors.white),),),body: WillPopScope(onWillPop: ()async{if(_lastTime==null||DateTime.now().difference(_lastTime)>Duration(seconds: 1)){_lastTime=DateTime.now();Fluttertoast.showToast(msg: "再点击一次退出app",fontSize: 16,backgroundColor: Colors.blue,textColor: Colors.white);return false;}return true;},child: Container(alignment: Alignment.center,child: Text("1秒内连续按两次返回键退出",style: TextStyle(fontSize: 30),),),),),);}
}

运行效果