double_tap_back_exit_app.dart 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  4. /// 双击返回退出
  5. class DoubleTapBackExitApp extends StatefulWidget {
  6. const DoubleTapBackExitApp({
  7. Key? key,
  8. required this.child,
  9. this.duration = const Duration(milliseconds: 2500),
  10. }) : super(key: key);
  11. final Widget child;
  12. /// 两次点击返回按钮的时间间隔
  13. final Duration duration;
  14. @override
  15. _DoubleTapBackExitAppState createState() => _DoubleTapBackExitAppState();
  16. }
  17. class _DoubleTapBackExitAppState extends State<DoubleTapBackExitApp> {
  18. DateTime? _lastTime;
  19. @override
  20. Widget build(BuildContext context) {
  21. return WillPopScope(
  22. onWillPop: _isExit,
  23. child: widget.child,
  24. );
  25. }
  26. Future<bool> _isExit() async {
  27. if (_lastTime == null || DateTime.now().difference(_lastTime!) > widget.duration) {
  28. _lastTime = DateTime.now();
  29. SmartDialog.compatible.showToast("再次点击退出应用");
  30. return Future.value(false);
  31. }
  32. // ToastUtil.cancelToast();
  33. await SystemNavigator.pop();
  34. return Future.value(true);
  35. }
  36. }