Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Make Double Press Back Button to Exit on Flutter App

In this example, we are going to show you how to make double press the back button to exit the app on Flutter. We are not going to use any package to achieve this feature. See the example below:

See this also: How to override Back Button and Show Exit Confirm in Flutter App

Double Back Button Press Exist App Example:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp( 
      home: MyApp()
  ));
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var ctime;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: WillPopScope(

             onWillPop: () {
                DateTime now = DateTime.now();
                if (ctime == null || now.difference(ctime) > Duration(seconds: 2)) { 
                     //add duration of press gap
                    ctime = now;
                    ScaffoldMessenger.of(context).showSnackBar(
                       SnackBar(content: Text('Press Back Button Again to Exit')) 
                    ); //scaffold message, you can show Toast message too.
                    return Future.value(false);
                }

                return Future.value(true);
             },

             child: Container( 
                color: Colors.lightBlue,
                //your content goes here.
             )
          )
      );
  }
}

Output on Back button Press:

In this way, you can add a Double back button press to exit feature on Flutter App.

No any Comments on this Article


Please Wait...