Flutter 实现安卓两次返回退出App

公司用flutter开发跨平台App,安卓老是不小心点击退出APP,自己就试着写了个点击两次退出APP的功能

直接上代码:



class AppExitConfirm extends StatefulWidget {

  final Widget child;

  AppExitConfirm({Key? key, required this.child}) : super(key: key);

  @override

  _AppExitConfirmState createState() => _AppExitConfirmState();

}

class _AppExitConfirmState extends State {

  int _flag = 0;

  @override

  Widget build(BuildContext context) {

    _checkContextInScaffold();

    return Platform.isAndroid

        ? WillPopScope(child: widget.child, onWillPop: _exitHandle)

        : widget.child;

  }

  Future _exitHandle() async {

    _flag ^= 1;

    toast('再次返回退出');

    Future.delayed(Duration(seconds: 2), () => _flag = 0);

    return _flag == 0;

  }

  void _checkContextInScaffold() {

    if (Scaffold.maybeOf(context) == null) {

      throw FlutterError('AppExitConfirm 必须使用Scaffold包裹.');

    }

  }

}

你可能感兴趣的:(Flutter 实现安卓两次返回退出App)