Repository: flutter
Issue: [go_router] pushReplacement causes "Null check operator used on a null value"
Labels: a: error message,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.13,found in release: 3.16

### Is there an existing issue for this?

- [X] I have searched the [existing package issues](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3Apackage)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### What package does this bug report belong to?

go_router

### What target platforms are you seeing this bug on?

Android, iOS

### Have you already upgraded your packages?

Yes

### Dependency versions

<details><summary>pubspec.lock</summary>

```lock
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
  async:
    dependency: transitive
    description:
      name: async
      sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
      url: "https://pub.dev"
    source: hosted
    version: "2.11.0"
  boolean_selector:
    dependency: transitive
    description:
      name: boolean_selector
      sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.1"
  characters:
    dependency: transitive
    description:
      name: characters
      sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
      url: "https://pub.dev"
    source: hosted
    version: "1.3.0"
  clock:
    dependency: transitive
    description:
      name: clock
      sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
      url: "https://pub.dev"
    source: hosted
    version: "1.1.1"
  collection:
    dependency: transitive
    description:
      name: collection
      sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687
      url: "https://pub.dev"
    source: hosted
    version: "1.17.2"
  cupertino_icons:
    dependency: "direct main"
    description:
      name: cupertino_icons
      sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d
      url: "https://pub.dev"
    source: hosted
    version: "1.0.6"
  fake_async:
    dependency: transitive
    description:
      name: fake_async
      sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
      url: "https://pub.dev"
    source: hosted
    version: "1.3.1"
  flutter:
    dependency: "direct main"
    description: flutter
    source: sdk
    version: "0.0.0"
  flutter_lints:
    dependency: "direct dev"
    description:
      name: flutter_lints
      sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
      url: "https://pub.dev"
    source: hosted
    version: "2.0.3"
  flutter_test:
    dependency: "direct dev"
    description: flutter
    source: sdk
    version: "0.0.0"
  flutter_web_plugins:
    dependency: transitive
    description: flutter
    source: sdk
    version: "0.0.0"
  go_router:
    dependency: "direct main"
    description:
      name: go_router
      sha256: e156bc1b2088eb5ece9351bccd48c3e1719a4858eacbd44e59162e98a68205d1
      url: "https://pub.dev"
    source: hosted
    version: "12.0.1"
  lints:
    dependency: transitive
    description:
      name: lints
      sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.1"
  logging:
    dependency: transitive
    description:
      name: logging
      sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340"
      url: "https://pub.dev"
    source: hosted
    version: "1.2.0"
  matcher:
    dependency: transitive
    description:
      name: matcher
      sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e"
      url: "https://pub.dev"
    source: hosted
    version: "0.12.16"
  material_color_utilities:
    dependency: transitive
    description:
      name: material_color_utilities
      sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41"
      url: "https://pub.dev"
    source: hosted
    version: "0.5.0"
  meta:
    dependency: transitive
    description:
      name: meta
      sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3"
      url: "https://pub.dev"
    source: hosted
    version: "1.9.1"
  path:
    dependency: transitive
    description:
      name: path
      sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917"
      url: "https://pub.dev"
    source: hosted
    version: "1.8.3"
  sky_engine:
    dependency: transitive
    description: flutter
    source: sdk
    version: "0.0.99"
  source_span:
    dependency: transitive
    description:
      name: source_span
      sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
      url: "https://pub.dev"
    source: hosted
    version: "1.10.0"
  stack_trace:
    dependency: transitive
    description:
      name: stack_trace
      sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5
      url: "https://pub.dev"
    source: hosted
    version: "1.11.0"
  stream_channel:
    dependency: transitive
    description:
      name: stream_channel
      sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.1"
  string_scanner:
    dependency: transitive
    description:
      name: string_scanner
      sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
      url: "https://pub.dev"
    source: hosted
    version: "1.2.0"
  term_glyph:
    dependency: transitive
    description:
      name: term_glyph
      sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
      url: "https://pub.dev"
    source: hosted
    version: "1.2.1"
  test_api:
    dependency: transitive
    description:
      name: test_api
      sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8"
      url: "https://pub.dev"
    source: hosted
    version: "0.6.0"
  vector_math:
    dependency: transitive
    description:
      name: vector_math
      sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.4"
  web:
    dependency: transitive
    description:
      name: web
      sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10
      url: "https://pub.dev"
    source: hosted
    version: "0.1.4-beta"
sdks:
  dart: ">=3.1.2 <4.0.0"
  flutter: ">=3.7.0"

```

</details>


### Steps to reproduce

1. Create a GoRouter with a _rootKey as a navigatorKey
```
GoRouter(initialLocation: '/1', navigatorKey: _rootNavigatorKey
```

2. Add a ShellRoute as a child route, and configure it's navigation keys: 
```
ShellRoute(
navigatorKey: _shellNavigatorKey,
parentNavigatorKey: _rootNavigatorKey
```

3. Add routes as children of the ShellRoute, also defining their parentNavigatorKey:
```
GoRoute(
  parentNavigatorKey: _shellNavigatorKey,
  path: '/1',
  builder: (context, state) => HomeScreen(),
),
GoRoute(
  parentNavigatorKey: _shellNavigatorKey,
  path: '/2',
  builder: (context, state) => SettingsScreen(),
)
```

4. Lastly, try navigating from HomeScreen to SettingsScreen using `pushReplacement`

Note: Full code is available below

### Expected results

App navigates to the next screen

### Actual results

App crashes with:

```
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building Builder:
Null check operator used on a null value

The relevant error-causing widget was: 
  MaterialApp MaterialApp:file:///Users/pcferreira/Projects/parkside/shell_navigator_key/lib/main.dart:41:24
When the exception was thrown, this was the stack: 
#0      RouteBuilder._buildPages (package:go_router/src/builder.dart:184:35)
```

Note 1: when navigating with `push`, the issue doesn't happen.
Note 2: when removing the `parentNavigatorKey` from HomeScreen and SettingsScreen, the issue doesn't happen

### Code sample

<details><summary>Code sample</summary>

```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

void main() {
  runApp(const MyApp());
}

class AppRouter {
  GoRouter get router => _goRouter;

  final _rootNavigatorKey = GlobalKey<NavigatorState>();
  final _shellNavigatorKey = GlobalKey<NavigatorState>();

  late final GoRouter _goRouter =
      GoRouter(initialLocation: '/1', navigatorKey: _rootNavigatorKey, routes: [
    ShellRoute(
        navigatorKey: _shellNavigatorKey,
        parentNavigatorKey: _rootNavigatorKey,
        builder: (context, state, child) => SampleGuard(child: child),
        routes: [
          GoRoute(
            parentNavigatorKey: _shellNavigatorKey,
            path: '/1',
            builder: (context, state) => HomeScreen(),
          ),
          GoRoute(
            parentNavigatorKey: _shellNavigatorKey,
            path: '/2',
            builder: (context, state) => SettingsScreen(),
          )
        ])
  ]);
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      themeMode: ThemeMode.dark,
      routerConfig: AppRouter().router,
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () => context.pushReplacement("/2"),
          child: Text("navigate"),
        ),
      ),
    );
  }
}

class SettingsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("2"),
      ),
    );
  }
}

class SampleGuard extends StatelessWidget {
  final Widget? child;

  const SampleGuard({super.key, this.child});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: child,
    );
  }
}

```

</details>


### Screenshots or Videos

<details>
<summary>Screenshots / Video demonstration</summary>

https://github.com/flutter/flutter/assets/108902/6de71d68-8fee-44cb-8909-6ba6b9205722

</details>


### Logs

<details><summary>Logs</summary>

```console
Performing hot restart...
Syncing files to device iPhone 13 mini...
Restarted application in 466ms.

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building Builder:
Null check operator used on a null value

The relevant error-causing widget was: 
  MaterialApp MaterialApp:file:///Users/pcferreira/Projects/parkside/shell_navigator_key/lib/main.dart:41:24
When the exception was thrown, this was the stack: 
#0      RouteBuilder._buildPages (package:go_router/src/builder.dart:184:35)
#1      RouteBuilder.tryBuild (package:go_router/src/builder.dart:142:9)
#2      RouteBuilder.build.<anonymous closure> (package:go_router/src/builder.dart:113:33)
#3      Builder.build (package:flutter/src/widgets/basic.dart:7619:48)
#4      StatelessElement.build (package:flutter/src/widgets/framework.dart:5367:49)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5297:15)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#7      StatelessElement.update (package:flutter/src/widgets/framework.dart:5373:5)
#8      Element.updateChild (package:flutter/src/widgets/framework.dart:3685:15)
#9      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5322:16)
#10     Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#11     ProxyElement.update (package:flutter/src/widgets/framework.dart:5628:5)
#12     Element.updateChild (package:flutter/src/widgets/framework.dart:3685:15)
#13     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5322:16)
#14     Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#15     StatelessElement.update (package:flutter/src/widgets/framework.dart:5373:5)
#16     Element.updateChild (package:flutter/src/widgets/framework.dart:3685:15)
#17     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5322:16)
#18     Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#19     ProxyElement.update (package:flutter/src/widgets/framework.dart:5628:5)
#20     Element.updateChild (package:flutter/src/widgets/framework.dart:3685:15)
#21     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5322:16)
#22     Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#23     ProxyElement.update (package:flutter/src/widgets/framework.dart:5628:5)
#24     Element.updateChild (package:flutter/src/widgets/framework.dart:3685:15)
#25     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5322:16)
#26     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5462:11)
#27     Element.rebuild (package:flutter/src/widgets/framework.dart:5016:7)
#28     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2779:19)
#29     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:916:21)
#30     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:360:5)
#31     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1297:15)
#32     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1227:9)
#33     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1085:5)
#34     _invoke (dart:ui/hooks.dart:170:13)
#35     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:401:5)
#36     _drawFrame (dart:ui/hooks.dart:140:31)
====================================================================================================

```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
➜  shell_navigator_key flutter doctor -v
[✓] Flutter (Channel stable, 3.13.4, on macOS 14.0 23A344 darwin-arm64, locale en-PT)
    • Flutter version 3.13.4 on channel stable at /Users/pcferreira/dev/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 367f9ea16b (7 weeks ago), 2023-09-12 23:27:53 -0500
    • Engine revision 9064459a8b
    • Dart version 3.1.2
    • DevTools version 2.25.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at /Users/pcferreira/Library/Android/sdk
    • Platform android-34, build-tools 33.0.1
    • ANDROID_HOME = /Users/pcferreira/Library/Android/sdk
    • ANDROID_SDK_ROOT = /Users/pcferreira/Library/Android/sdk
    • Java binary at: /Users/pcferreira/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/223.8836.35.2231.10406996/Android
      Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15A507
    • CocoaPods version 1.13.0

[✗] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[✓] Android Studio (version 2022.3)
    • Android Studio at /Users/pcferreira/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/223.8836.35.2231.10406996/Android
      Studio.app/Contents
    • 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
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] Android Studio (version 2022.3)
    • Android Studio at /Users/pcferreira/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/223.8836.35.2231.10671973/Android
      Studio.app/Contents
    • 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
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] VS Code (version 1.83.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.74.0

[✓] Connected device (3 available)
    • iPhone de Paulo Cesar (mobile) • 00008020-0019555134D2002E            • ios          • iOS 17.0.3 21A360
    • iPhone 13 mini (mobile)        • 1CB43387-D8C0-476D-B452-AECEBB572577 • ios          • com.apple.CoreSimulator.SimRuntime.iOS-17-0 (simulator)
    • macOS (desktop)                • macos                                • darwin-arm64 • macOS 14.0 23A344 darwin-arm64
    ! Error: Browsing on the local area network for Parkside 12 pro. Ensure the device is unlocked and attached with a cable or associated with the same local area
      network as this Mac.
      The device must be opted into Developer Mode to connect wirelessly. (code -27)

[✓] Network resources
    • All expected network resources are available.

```

</details>