Repository: flutter
Issue: Navigator.pushReplacement + Navigator.pop results in assertion failure
Labels: c: crash,framework,f: routes,a: error message,has reproducible steps,P2,team-framework,triaged-framework,found in release: 3.24,found in release: 3.27

### Steps to reproduce

I'm working on an application which has a profile editor screen. When the app first opened, then the profile editor is the first screen to add the profile. Then it is reused when the profile is edited. This component calls a Navigator.pushReplacement on save to redirect to the home screen. It resulted in the pasted log message when it was used to create the profile and not when it was used to edit it. 

I've analyzed it and I could reproduce it with the sample below. It turned out that a lower level component has called Navigator.pop after it called a callback which called pushReplacement. 

I know it's dumb and I guess it should not be used like this, but it is quite easy to get into this situation when you have multiple levels of components + callbacks. I could fix it by not calling pop in the low level component.

However, I open this ticket, because I've found several other unsolved tickets with really similar messages and stack traces. So I guess other devs ran into this situation as well. Some examples

- https://github.com/flutter/flutter/issues/153217
- https://github.com/flutter/flutter/issues/149581
- https://github.com/flutter/flutter/issues/132541
- https://github.com/flutter/flutter/issues/132380
- https://github.com/flutter/flutter/issues/131086
- https://github.com/flutter/flutter/issues/82035

Steps:

1. Create a project with the provided sample
2. Run it (was tested on Debian 12 and with an android emulator)
3. Click on the save button

### Expected results

The assertion does not fail. Even if pop was called after the pushReplacement, the replace is done as expected.

### Actual results

The assertion fails in the situation described in "Steps to reproduce".

### Code sample

<details open><summary>Code sample</summary>

```dart
[Paste your code here]
```

</details>


### Screenshots or Video

<details open>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details open><summary>Logs</summary>

```console
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Navigator-[GlobalObjectKey<NavigatorState>
_WidgetsAppState#100be](dirty, dependencies: [HeroControllerScope, UnmanagedRestorationScope],
state: NavigatorState#e3fa4(tickers: tracking 1 ticker)):
'package:flutter/src/widgets/navigator.dart': Failed assertion: line 5609 pos 12:
'_history.isNotEmpty': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially
more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.yml

The relevant error-causing widget was:
  MaterialApp MaterialApp:file:///home/vargab95/workspace/vargary/babybloom/lib/main.dart:94:18

When the exception was thrown, this was the stack:
#2      NavigatorState.build (package:flutter/src/widgets/navigator.dart:5609:12)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:5729:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5617:15)
#5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5780:11)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:5333:7)
#7      BuildScope._tryRebuild (package:flutter/src/widgets/framework.dart:2693:15)
#8      BuildScope._flushDirtyElements (package:flutter/src/widgets/framework.dart:2752:11)
#9      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3048:18)
#10     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1162:21)
#11     RendererBinding._handlePersistentFrameCallback
(package:flutter/src/rendering/binding.dart:468:5)
#12     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1397:15)
#13     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1318:9)
#14     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1176:5)
#15     _invoke (dart:ui/hooks.dart:312:13)
#16     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:419:5)
#17     _drawFrame (dart:ui/hooks.dart:283:31)
(elided 2 frames from class _AssertionError)

════════════════════════════════════════════════════════════════════════════════════════════════════
```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.24.4, on Debian GNU/Linux 12 (bookworm) 6.1.0-26-amd64, locale
    en_US.UTF-8)
    • Flutter version 3.24.4 on channel stable at /home/vargab95/devtools/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 603104015d (12 days ago), 2024-10-24 08:01:25 -0700
    • Engine revision db49896cf2
    • Dart version 3.5.4
    • DevTools version 2.37.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /home/vargab95/Android/Sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /var/lib/flatpak/app/com.google.AndroidStudio/current/active/files/extra/android-studio/jbr/bin/java
    • Java version OpenJDK Runtime Environment (build 21.0.3+-12282718-b509.11)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = /var/lib/flatpak/exports/bin/com.google.Chrome

[✓] Linux toolchain - develop for Linux desktop
    • Debian clang version 14.0.6
    • cmake version 3.25.1
    • ninja version 1.11.1
    • pkg-config version 1.8.1

[!] Android Studio (version unknown)
    • Android Studio at /var/lib/flatpak/app/com.google.AndroidStudio/current/active/files/extra/android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to determine Android Studio version.
    • android-studio-dir = /var/lib/flatpak/app/com.google.AndroidStudio/current/active/files/extra/android-studio
    • Java version OpenJDK Runtime Environment (build 21.0.3+-12282718-b509.11)

[✓] VS Code (version 1.95.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.98.0

[✓] VS Code (version 1.94.2)
    • VS Code at /var/lib/flatpak/app/com.visualstudio.code/x86_64/stable/active/files/extra/vscode
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 14 (API 34) (emulator)
    • Linux (desktop)              • linux         • linux-x64      • Debian GNU/Linux 12 (bookworm) 6.1.0-26-amd64
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 130.0.6723.91

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.
```

</details>