Home > Mobile >  How to switch the screen smoothly?
How to switch the screen smoothly?

Time:01-14

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);

CodePudding user response:

Using pushReplacement insted of push

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

CodePudding user response:

Using pushReplacement insted of push

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related