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

前端 未结 9 538
野趣味
野趣味 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:11

    You can try this package.

    Inside a Scaffold that wraps all your Widgets, place the DoubleBackToCloseApp passing a SnackBar:

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: DoubleBackToCloseApp(
              child: Home(),
              snackBar: const SnackBar(
                content: Text('Tap back again to leave'),
              ),
            ),
          ),
        );
      }
    }
    

    Old answer

    You can also opt for a solution involving SnackBar. It's not as simple as Andrey Turkovsky's answer, but it's quite more elegant and you won't depend on a library.

    class _FooState extends State {
      static const snackBarDuration = Duration(seconds: 3);
    
      final snackBar = SnackBar(
        content: Text('Press back again to leave'),
        duration: snackBarDuration,
      );
    
      DateTime backButtonPressTime;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          // The BuildContext must be from one of the Scaffold's children.
          body: Builder(
            builder: (context) {
              return WillPopScope(
                onWillPop: () => handleWillPop(context),
                child: Text('Place your child here'),
              );
            },
          ),
        );
      }
    
      Future handleWillPop(BuildContext context) async {
        final now = DateTime.now();
        final backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
            backButtonPressTime == null ||
                now.difference(backButtonPressTime) > snackBarDuration;
    
        if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
          backButtonPressTime = now;
          Scaffold.of(context).showSnackBar(snackBar);
          return false;
        }
    
        return true;
      }
    }
    

提交回复
热议问题