skip to Main Content

I have three screens: 1, 2, and 3.
I want to switch from screen 2 to screen 3, but when I pop screen 2 and push screen 3, then it shows screen 1 for a while, then it shows screen 3, so is there any way to switch screens using pop after push or not?

this code not expectations

Navigator.push(
  context,
  MaterialPageRoute<Widget>(
    builder: (context) => widget,
  ),
);
Navigator.pop(context);

4

Answers


  1. Using pushReplacement insted of push

    Navigator.pushReplacement(
      context,
      MaterialPageRoute<Widget>(
        builder: (context) => widget,
      ),
    );
    
    Login or Signup to reply.
  2. Using pushReplacement insted of push

    Navigator.pushReplacement(
    context,
    MaterialPageRoute(
    builder: (context) => widget,
    ),
    );

    Login or Signup to reply.
  3. The behavior you’re describing is likely because when you call Navigator.pop(context), it removes the current screen (screen 2) from the navigation stack, but the framework hasn’t yet had a chance to build and display the new screen (screen 3) that you pushed. So, for a brief moment, the previous screen (screen 1) is visible.

    One way to switch screens without that flicker is to use Navigator.pushReplacement instead of Navigator.push followed by Navigator.pop. Navigator.pushReplacement removes the current screen from the navigation stack and replaces it with the new screen, all in one step.

    Example:

    Navigator.pushReplacement(
      context,
      MaterialPageRoute<Widget>(
        builder: (context) => widget3,
      ),
    );
    

    This will directly switch from screen 2 to screen 3.

    Login or Signup to reply.
  4. It is generally not recommended to use both Navigator.push() and Navigator.pop() together in the same function call, as this can cause unexpected behavior. Instead, you can use Navigator.replace() to replace the current screen with a new one, or use Navigator.pushNamedAndRemoveUntil() to push a new screen and remove all the screens that come before it.

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