In this tutorial, I will show you how to implement Double click to exit the app in a flutter, with the help of WillpopScope widget. WillpopScope has a method which will help Use of Override back Button Functionality and its very easy to use.

With the Help of WillpopScope, it will show FlutterToast in the Bottom Bar of App Screen which will show Alert Message Just Below Image.

back button

How to Exit an app by Double Click on Back Button in Flutter

If you Don’t know how to Create a Flutter app, check out Getting started with Flutter official tutorial.

//main.dart
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        home: Scaffold(
          body: BackButton()
        ));
  }
}

After Creating a Simple MyApp StatelesWidget, Now Create BackButton.dart file. it will contain Main code Or Login of Back Button Functionality. In this BackButton.dart File, we’ll implement WillPopScope as the root of the Widget.

//BackButton
class BackButton extends StatefulWidget {
  @override
  _BackButtonState createState() => _BackButtonState();
}
class _BackButtonState extends State<BackButton> {
  DateTime backbuttonpressedTime;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        onWillPop: onWillPop,
        child: Center(
          child: Text('Double Click to exit app'),
        ),
      ),
    );
  }
}

Above code is a Simple stateful widget, where we add WillPopScope.

WillPopScope has property onwillpop in that we have written onWillPop method which we’ll invoke back press functionality. Below code is the Snippet of onWillPop method logic.

Future<bool> onWillPop() async {
  DateTime currentTime = DateTime.now();

  //Statement 1 Or statement2
  bool backButton = backbuttonpressedTime == null ||
      currentTime.difference(backbuttonpressedTime) > Duration(seconds: 3);

  if (backButton) {
    backbuttonpressedTime = currentTime;
    Fluttertoast.showToast(
        msg: "Double Click to exit app",
        backgroundColor: Colors.black,
        textColor: Colors.white);
    return false;
  }
  return true;
}

The Future _onWillPop() will return a flutter toast which will return either True whenever user double click on the back button Or False Nothing will happen

You can see the full source code of the project here.

View on github

🤝 Show Some Support

If you liked the app, show some love Here  ⭐️

Best tutorial to learn Flutter