double_tap_back_exit_app.dart 1.2 KB

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