Flutter实现1秒内连续按两次返回键退出。

2022年8月7日 1032点热度 0人点赞 0条评论

使用WillPopScope的默认构造函数实现,onWillPop回调函数返回的Future最终值为false时,当前路由不出栈(不会返回)。
主要是为了避免用户误触返回按钮导致app退出。

<code>import &#039;package:flutter/material.dart&#039;;

main()=&gt;runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(&quot;1秒内连续按两次返回键退出&quot;),
          centerTitle: true,
        ),
        body: const MyHomePage()
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  DateTime? _dateTime;//上次点击的时间

  @override
  Widget build(BuildContext context) {
    return WillPopScope(

      onWillPop: () async {
          _dateTime = DateTime.now();
          if(_dateTime == null || DateTime.now().difference(_dateTime!) &gt; const Duration(seconds: 1)){
            _dateTime = DateTime.now();
            return false;
          }
          return true;
      },
      child: Container(
        alignment: Alignment.center,
        child: const Text(&quot;1秒内连续按两次返回键退出&quot;),
      ),
    );
  }
}</code>

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论