Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

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

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". The following second press, app exits. Of course, the time between two press must be not long.

How to do it in flutter?

question from:https://stackoverflow.com/questions/53496161/how-to-write-a-double-back-button-pressed-to-exit-app-using-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is an example of my code (I've used "fluttertoast" for showing toast message, you can use snackbar or alert or anything else)

DateTime currentBackPressTime;

@override
Widget build(BuildContext context) {
  return Scaffold(
    ...
    body: WillPopScope(child: getBody(), onWillPop: onWillPop),
  );
}

Future<bool> onWillPop() {
    DateTime now = DateTime.now();
    if (currentBackPressTime == null || 
        now.difference(currentBackPressTime) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      Fluttertoast.showToast(msg: exit_warning);
      return Future.value(false);
    }
    return Future.value(true);
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...