How to write a double back button pressed to exit app using flutter

前端 未结 9 526
野趣味
野趣味 2020-12-24 13:39

I\'m new to flutter, and I saw many android apps can exit when double press back button.

The first time press back button, app shows a toast\"press again to exit app

9条回答
  •  旧巷少年郎
    2020-12-24 14:30

    Unfortunately none of them worked for me, I have written one generic class (widget) to handle double tap exit. If someone is interested

    class DoubleBackToCloseWidget extends StatefulWidget {
      final Widget child; // Make Sure this child has a Scaffold widget as parent.
    
      const DoubleBackToCloseWidget({
        @required this.child,
      });
    
      @override
      _DoubleBackToCloseWidgetState createState() =>
          _DoubleBackToCloseWidgetState();
    }
    
    class _DoubleBackToCloseWidgetState extends State {
      int _lastTimeBackButtonWasTapped;
      static const exitTimeInMillis = 2000;
    
      bool get _isAndroid => Theme.of(context).platform == TargetPlatform.android;
    
      @override
      Widget build(BuildContext context) {
        if (_isAndroid) {
          return WillPopScope(
            onWillPop: _handleWillPop,
            child: widget.child,
          );
        } else {
          return widget.child;
        }
      }
    
      Future _handleWillPop() async {
        final _currentTime = DateTime.now().millisecondsSinceEpoch;
    
        if (_lastTimeBackButtonWasTapped != null &&
            (_currentTime - _lastTimeBackButtonWasTapped) < exitTimeInMillis) {
          Scaffold.of(context).removeCurrentSnackBar();
          return true;
        } else {
          _lastTimeBackButtonWasTapped = DateTime.now().millisecondsSinceEpoch;
          Scaffold.of(context).removeCurrentSnackBar();
          Scaffold.of(context).showSnackBar(
            _getExitSnackBar(context),
          );
          return false;
        }
      }
    
      SnackBar _getExitSnackBar(
        BuildContext context,
      ) {
        return SnackBar(
          content: Text(
            'Press BACK again to exit!',
            color: Colors.white,
          ),
          backgroundColor: Colors.red,
          duration: const Duration(
            seconds: 2,
          ),
          behavior: SnackBarBehavior.floating,
        );
      }
    }
    
    

    Use this class following way:

    class Dashboard extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
            body: DoubleBackToCloseWidget(
              child: Container(
                child: Column(
                  children: [
                    const Text('Hello there'),
                    const Text('Hello there again'),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    
    
    

提交回复
热议问题