Flutter基础-030-WillPopScope

201 阅读1分钟

硬件返回键的监控,注意

构造方法
const WillPopScope({
    Key key,
    @required this.child, // 可以给出一些提示信息
    @required this.onWillPop,// 点击硬件返回键调用此方法
  })

image.png

class _MyHomePageState extends State<MyHomePage> {
  DateTime lastTime;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: WillPopScope(
            child: SizedBox(
              width: 50,
              height: 50,
              child: Text("Back"),
            ),
          onWillPop: () async {
              //连点两次,间隔不超过1秒时,认为是真的想退出
              if(lastTime==null || DateTime.now().difference(lastTime)>Duration(seconds: 1)){
                lastTime = DateTime.now();
                print(false);
                return false;// 不退出
              }
              print(true);
              return true;// 退出
          },
        ),
      ),
    );
  }
}