skip to Main Content

I am using the flutter package back_pressed (https://pub.dev/packages/back_pressed), I also tried implementing my own code similar to theirs which uses WillPopScope.

The back_pressed plugin is working fine all over my app, except for on 1 of my screens… this screen is not listening and is doing the default behavior for when the back button is pressed on Android.

@override
  Widget build(BuildContext context) {
    SetSizes();
    return WillPopScope(
      onWillPop: () { exit(0); },
      child: Content(),
    );
  }

I have also tried this:

@override
  Widget build(BuildContext context) {
    SetSizes();
    return OnBackPressed(child: Content(), perform: LeaveScreen);
  }
void LeaveScreen() {
    print("..........................Back pressed..........................");
    var navIndex = Provider.of<AppData>(context, listen: false).navIndex;
    navIndex.jumpToTab(1);
  }

The OnBackPressed code is working everywhere else in my app, except for this screen.

2

Answers


  1. Chosen as BEST ANSWER

    The problem was caused because I was using a plugin for my bottom navigation, the navigation was loaded in a controller file, then the controller loaded the screens content from another file...

    Issue was I needed to implement WillPopScope on the navigation controller file.

    @override
      Widget build(BuildContext context) {
        _controller = Provider.of<AppData>(context, listen: false).navIndex;
        return WillPopScope(
          onWillPop: () async {
            if (_controller.index == 0) {
              FlutterAppMinimizer.minimize();
              return false;
            }
            return true;
          },
          child: PersistentTabView(...
    

  2. the problem is the exit(0). here is my WillPopScope implementation which works in my whole app:

    ...
    return WillPopScope(
          onWillPop: () async => false,
          child: Scaffold(
    ...
    

    you neet to use async => false, since onWillPop which is {required Future<bool> Function()? onWillPop} expects a Future Bool not an int or something.

    Further explanation on onWillPop:

    Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
    If the callback returns a Future that resolves to false, the enclosing route will not be popped.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search