首页 > 其他 > 详细

Flutter_04_实现连续两次返回退出

时间:2021-08-06 17:30:14      阅读:16      评论:0      收藏:0      [点我收藏+]
/// 封装一个连续按两次返回键退出页面的组件
/// child 子组件
/// delay 两次返回间隔时间
class UseWillPopScope extends StatefulWidget {
  final Widget child;
  final Duration delay;

  const UseWillPopScope(
      {Key? key, this.delay = const Duration(seconds: 1), required this.child})
      : super(key: key);

  @override
  _UseWillPopScopeState createState() => _UseWillPopScopeState();
}

class _UseWillPopScopeState extends State<UseWillPopScope> {
  DateTime? _lastWillPopAt;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: widget.child,
      onWillPop: () async {
        print(_lastWillPopAt);
        if (_lastWillPopAt == null ||
            _lastWillPopAt != null &&
                DateTime.now().difference(_lastWillPopAt!) > widget.delay) {
          _lastWillPopAt = DateTime.now();
          Fluttertoast.showToast(
            msg: ‘再按一次退出Flutter Go‘,
            fontSize: 16.0,
            backgroundColor: Colors.grey,
            gravity: ToastGravity.CENTER,
          );
          return false;
        }
        return true;
      },
    );
  }
}

Flutter_04_实现连续两次返回退出

原文:https://www.cnblogs.com/carp-li/p/15108031.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!