skip to Main Content

i added pop scope to my code to go to prev page when the back button on phone is pressed, but instead of going to prev page, it closed the app instead. I don’t want to close the app.
this is where i put my pop scope

@override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: true,
      onPopInvoked: (bool didPop) async {
        if (didPop) {
          return;
        }
        Navigator.pop(context); 
      },
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          leading: Builder(
            builder: (BuildContext context) {
              return IconButton(
                icon: const Icon(Icons.arrow_back),
                color: Colors.black,
                onPressed: () {
                  Navigator.pop(context);
                },
              );
            },
          ),
          title: Text(
            'Pengajuan',
            style: TextStyle(color: Colors.black),
          ),
        ),
//body
    );
  }`

3

Answers


  1. Are you sure you are redirecting to this page correctly? I don’t see a problem with the code you wrote.

    Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
    

    With this code, can you redirect to the PopScope wrapped screen?

    Login or Signup to reply.
  2. Share your router config to see if you have StatefulShellRoute or somelse main route to block pop out that close your app. Navigator.of(context).pop() is a good way.

    Login or Signup to reply.
  3. Why are you using a PopScope in your case?

    PopScope is for intercepting pop and doing something before poping or cancel the pop based on your application logic.

    If you just need to pop te current screen, just do a navigator.pop properly:

    onPressed: () {
        Navigator.of(context).pop(context);
    },
    

    You can also verify if you are not on the first screen before poping, because if it is the case you will encounter an error and have a black screen.

    onPressed: () {
        if (Navigator.of(context).canPop()) {
            Navigator.of(context).pop(context);
        }
    },
    

    I don’t think it is your case, but if you need to pop to the first screen, you can use this:

    Navigator.of(context).popUntil((route) => route.isFirst);

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