Flutter Double Press to Close Application

Last updated Nov 12, 2021

In this tutorial, we will see how you can get double tap to close the application functionality in Flutter.

Let's Start

Step 1: Create a new Flutter Application or Open an existing application.

Step 2: Add a line like this to your package's pubspec.yaml

dependencies:
  double_back_to_close_app: ^2.0.1

 

Step 3: Once installed go to your home page or homescreen where you want your app to close and warp your home screen widget with a widget called DoubleBackToCloseApp.

for example: 

DoubleBackToCloseApp(

snackbar:

child:

)

 

wrapping this widget homescreen will be your child widget and for snackbar you can add snackbar that will pop up when you press back button from homescreen.

for example: 

 snackBar: const SnackBar(

          content: Text('Press again to close'),

          behavior: SnackBarBehavior.floating,

          backgroundColor: Colors.black12,

        ),

With this you will get double back to close the app functionality in Flutter.

 

Complete Source Code to Double press back button to close the application

import 'package:double_back_to_close_app/double_back_to_close_app.dart';

import 'package:flutter/material.dart';

 

void main() {

  runApp(MyApp());

}

 

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      debugShowCheckedModeBanner: false,

      home: Demo(),

    );

  }

}

 

class Demo extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        backgroundColor: Colors.transparent,

        title: Text('Demo App'),

      ),

      extendBodyBehindAppBar: true,

      body: DoubleBackToCloseApp(

        snackBar: const SnackBar(

          content: Text('Press again to close'),

          behavior: SnackBarBehavior.floating,

          backgroundColor: Colors.black12,

        ),

        child: Container(

          decoration: const BoxDecoration(

              image: DecorationImage(

            image: AssetImage('assets/images/image.jpg'),

            fit: BoxFit.cover,

          )),

        ),

      ),

    );

  }

}

 

 

Output:

 

Video Tutorial

 

Conclusion: In this way, we have learned how we can get double back to close the app functionality in Flutter.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1025 Views