skip to Main Content
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'backend/firebase/firebase_config.dart';
import 'flutter_flow/flutter_flow_theme.dart';
import 'flutter_flow/flutter_flow_util.dart';
import 'flutter_flow/internationalization.dart';
import 'flutter_flow/nav/nav.dart';
import 'index.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  GoRouter.optionURLReflectsImperativeAPIs = true;
  usePathUrlStrategy();
  await initFirebase();

  await FlutterFlowTheme.initialize();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  State<MyApp> createState() => _MyAppState();

  static _MyAppState of(BuildContext context) =>
      context.findAncestorStateOfType<_MyAppState>()!;

}

class _MyAppState extends State<MyApp> {
  Locale? _locale;
  ThemeMode _themeMode = FlutterFlowTheme.themeMode;

  late AppStateNotifier _appStateNotifier;
  late GoRouter _router;

  bool displaySplashImage = true;

  @override
  void initState() {
    super.initState();

    _appStateNotifier = AppStateNotifier.instance;
    _router = createRouter(_appStateNotifier);

    Future.delayed(Duration(milliseconds: 3000),
        () => setState(() => _appStateNotifier.stopShowingSplashImage()));
  }

  void setLocale(String language) {
    setState(() => _locale = createLocale(language));
  }

  void setThemeMode(ThemeMode mode) => setState(() {
        _themeMode = mode;
        FlutterFlowTheme.saveThemeMode(mode);
      });

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Refereevision App',
      localizationsDelegates: [
        FFLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      locale: _locale,
      supportedLocales: const [
        Locale('en'),
      ],
      theme: ThemeData(
        brightness: Brightness.light,
        useMaterial3: false,
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        useMaterial3: false,
      ),
      themeMode: _themeMode,
      routerConfig: _router,
    );
  }
}

I need to implement the functionality that the app exits when back button is presses twice.
I am new to flutter programming and am confused where to implement this functionality in the above code.
FYI Android version 14.
Currently on pressing the back button it just re-navivgates the entire flow in the reverse.
Kindly help.

3

Answers


  1. To implement the functionality where the app exits when the back button is pressed twice, you can use the PopScope widget. This widget allows you to intercept the back button press and perform custom actions. Here’s an example of how you can use it:

    import 'package:flutter/material.dart';
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    bool canPop = false;
    
      @override
      Widget build(BuildContext context) {
        return PopScope(
          canPop: canPop,
          onPopInvoked:  (didPop)  {
            if (!canPop) {
              canPop = true;
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('Press back again to exit'),
                ),
              );
             
            }
            
          },
          child: Scaffold(
            appBar: AppBar(
              title: Text('Double Back Press to Exit'),
            ),
            body: Center(
              child: Text('Press the back button twice to exit'),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Check this code

     Widget build(BuildContext context) {
        return MaterialApp(
          home: WillPopScope(
            onWillPop: () async {
              DateTime currentTime = DateTime.now();
              if (_lastPressedAt == null ||
                  currentTime.difference(_lastPressedAt!) > Duration(seconds: 2)) {
                _lastPressedAt = currentTime;
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text('Press back again to exit'),
                  ),
                );
                return false;
              }
              return true;
            },
            child: Scaffold(
              appBar: AppBar(
                title: Text('Title'),
              ),
              body: Container(),
            ),
          ),
        );
      }
    
    Login or Signup to reply.
  3. Try this code

    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;
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text("Press back to exit"),
          ));
          return Future.value(false);
        }
        return Future.value(true);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search