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
Using
pushReplacement
insted ofpush
Using pushReplacement insted of push
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => widget,
),
);
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:
This will directly switch from screen 2 to screen 3.
It is generally not recommended to use both
Navigator.push()
andNavigator.pop()
together in the same function call, as this can cause unexpected behavior. Instead, you can useNavigator.replace()
to replace the current screen with a new one, or useNavigator.pushNamedAndRemoveUntil()
to push a new screen and remove all the screens that come before it.