When pressing the back button the application closes in flutter?
Asked Answered
T

8

8

As the title says after pressing the back button, the application closes.

Container(
      margin: EdgeInsets.only(left: 20, top: 8),
      decoration: BoxDecoration(
          color: colorYellow,
          borderRadius: BorderRadius.all(Radius.circular(20))),
      height: 40,
      width: 40,
      child: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.white, size: 20),
        onPressed: () => Navigator.of(context).pop(),
      ),
    ),
Trombidiasis answered 25/5, 2021 at 7:44 Comment(5)
I don't think you need to put true inside pop(). Maybe that's the problem? Can you give more code so we can check if there is something you are missing?Affranchise
i am also try with out true its also not workingTrombidiasis
The reason that the app is crashing might be because Flutter can't find anything to pop() out of. Is there any error given in the terminal? Maybe you can try Navigator.pop(context).Affranchise
i am applying this one also . same issueTrombidiasis
Hi! Don't actually understand what you want to get and whats wrong. Please explain.Overliberal
E
16

You can try changing android:enableOnBackInvokedCallback in AndroidManifest from true to false.

android>app>src>main>AndroidManifest.xml

Before

android:enableOnBackInvokedCallback="true"

After

android:enableOnBackInvokedCallback="false"
Entranceway answered 31/10, 2023 at 7:22 Comment(1)
I had the same issue, but this solution worked for me. @Parth-Prajapati Should mark this as the answer. After updating the code in the manifest file, I had to uninstall the app and install it again to start fresh.Ransdell
D
5

I was getting the same issue. When implemented flutter_stripe. Changing **FlutterFragmentActivity** to **FlutterActivity** solved the Issue. Don't know the cause


Delate answered 12/8, 2023 at 8:35 Comment(3)
i did the same but now stripe initialization getting error, So how to handle tha?Clingfish
setting android:enableOnBackInvokedCallback to false in menifest file worked for me. I was also having this issue while integrating stripePessimism
thanx Rehan worked for me as well with local_auth plugin need FlutterfragmentactivityBusby
A
3

Wrap your Scaffold with WillPopScope. Whenever the back button is pressed, you will get a callback at onWillPop, which returns a Future. If the Future returns true, the screen is popped.

 @override
 Widget build(BuildContext context) {
    return WillPopScope(
    onWillPop: () async {
        // await showDialog or Show add banners or whatever
        // return true if the route to be popped
         return false; // return false if you want to disable device back button click
       },
      child: Scaffold(),
     ),
  };

return false; which means your application not going to close on back button click

EDIT JUNE 2024

The WillPopScope widget in flutter is deprecated. The alternative widget is PopScope. This is how you can use it.

PopScope(
  canPop: false,
  onPopInvoked : (didPop){
   //---Your logic goes here---//
  },
)
Antiworld answered 25/5, 2021 at 14:16 Comment(1)
This is deprecatedKillough
D
3

WillPopScope is now deprecated after update 3.12.2, instead you can use PopScope

PopScope(
  canPop: false,
  onPopInvoked : (didPop){
   // logicenter code here
 }
Dworman answered 2/5 at 19:19 Comment(1)
This answer has worked for me 👍Procreant
I
2

Use Navigator.pop(context); instead of Navigator.of(context).pop()

Inconsistency answered 25/5, 2021 at 7:56 Comment(3)
i am applying this one also . same issueTrombidiasis
Can you paste your issue on here ?Inconsistency
no error display app is crash when click on itTrombidiasis
R
1
  Future<bool> onBackPress(context) {
        return showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title: Text('Do you wish to exit?'),
                  actions: <Widget>[
                    TextButton(
                      child: Text('Cancel'),
                      onPressed: () => {Navigator.pop(context, false)},
                    ),
                    TextButton(
                        onPressed: () => {Navigator.pop(context, true)},
                        child: Text('Exit'))
                  ],
                ));
      }
    
    @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () => onBackPress(context),
          child: SafeArea(),
     )};
Rep answered 25/5, 2021 at 8:46 Comment(0)
R
0

i am using the popscope but when i press the back button before loading the data i am getting the black screen instead of popup. when i press the back button again the app is closing

Rhamnaceous answered 26/5 at 7:19 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Rinker
D
0

I encountered the same issue with my Flutter application where pressing the back button caused the app to close. I managed to resolve it using the back_button_interceptor package.

Here's the solution that worked for me:

  1. Add the back_button_interceptor package to your pubspec.yaml:
dependencies:
  back_button_interceptor: ^5.0.0
  1. Implement the interceptor to handle the back button behavior:
import 'package:back_button_interceptor/back_button_interceptor.dart';
import 'package:flutter/services.dart';

bool _routeInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
  // Get the current navigation state
  var navigationState = Navigator.of(appRouter.navigatorKey.currentContext!);
  
  // If the keyboard is open, close it
  if (MediaQuery.of(appRouter.navigatorKey.currentContext!).viewInsets.bottom > 0) {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    return true;
  }
  
  // If we can pop the screen, pop it
  if (navigationState.canPop()) {
    navigationState.pop();
    return true;
  }
  
  return false;
}

@override
void initState() {
  super.initState();
  // Register the interceptor
  BackButtonInterceptor.add(_routeInterceptor);
}

@override
void dispose() {
  // Unregister the interceptor
  BackButtonInterceptor.remove(_routeInterceptor);
  super.dispose();
}

This interceptor does the following:

If the keyboard is open, it closes the keyboard and prevents the back button from performing its default action. If the keyboard is not open and the current route can be popped, it pops the route. This solution ensures that pressing the back button will either close the keyboard or navigate back without closing the app unexpectedly.

Dematerialize answered 19/6 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.