Repository: flutter
Issue: Rebuilding nested navigator causes focus loss in top navigator
Labels: framework,f: routes,has reproducible steps,P2,found in release: 3.3,found in release: 3.4,team-framework,triaged-framework

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

My app is build with a MaterialApp.router() as the outmost widget.

The routerDelegate is a navigator, which is the top navigator. The pages of this navigator is switching between a small and a large scaffold based on MediaQuery.of(context).size.

The inner navigator has a lot of pages, these pages can't all be const as some of them require a parameter, it could be a specific id for that page so it knows what info to show. Also when accessing the page via an URL the id can be specified there. So as I see it I have no way of making sure all pages are const.

The problem is, that because I use MediaQuery.of() around the inner navigator, it naturally causes a lot of rebuilds. So for example, having a TextField in a Drawer on the top navigator, or just anywhere above the inner navigator, that TextField will lose focus when the keyboard appears because the inner navigator pages rebuilds because they are not const.

## Steps to Reproduce

<!-- Please include full steps to reproduce so that we can reproduce the problem. -->

1. Execute `flutter run` on the code sample on a device with on screen keyboard <!-- (see "Code sample" section below) -->
2. Try the different TextFields
3. Notice how the one in the Drawer and the one in the bottom makes the keyboard disappear immediately

**Expected results:** <!-- what did you want to see? -->
I expect that the TextField in the top navigator works just as the TextFeild in the inner navigator.

**Actual results:** <!-- what did you see? -->
The top navigator loses focus for some reason when the inner navigator rebuilds, and therefore TextFields are unusable.
There are probably other widgets that has the same problem, but I only tested with TextField.

![navigatorerror](https://user-images.githubusercontent.com/6707330/192224066-6a1da3bf-a40f-433c-a947-2ea0c6e33470.gif)

<details>
<summary>Code sample</summary>
https://github.com/Keetz/nested-navigator-error

<!--
      Please create a minimal reproducible sample that shows the problem
      and attach it below between the lines with the backticks.

      To create it you can use `flutter create bug` command and update the `main.dart` file.

      Alternatively, you can use https://dartpad.dev/
      which is capable of creating and running small Flutter apps.

      Without this we will unlikely be able to progress on the issue, and because of that
      we regretfully will have to close it.
-->

The top navigator:
```
Navigator(
  key: navigatorKey,
  pages: <Page<dynamic>>[
    MaterialPage<Page<dynamic>>(
      child: MediaQuery.of(context).size.width < 400
          ? SmallScaffold(innerNavigatorKey: innerNavigatorKey)
          : LargeScaffold(innerNavigatorKey: innerNavigatorKey),
    )
  ],
  onPopPage: (Route<dynamic> route, dynamic result) {
    if (!route.didPop(result)) {
      return false;
    }
    notifyListeners();
    return true;
  },
)
```

The SmallScaffold:
```
Scaffold(
  appBar: AppBar(),
  drawer: const Drawer(child: Center(child: TextField())), // This textfield loses focus immediately!
  body: Column(
    children: [
      Expanded(
        child: Router<dynamic>(
          routerDelegate:
              InnerRouterDelegate(navigatorKey: innerNavigatorKey),
        ),
      ),
      const Divider(),
      const SizedBox(
        width: 200,
        height: 50,
        child: TextField(), // This textfield loses focus immediately!
      ),
      const SizedBox(height: 20)
    ],
  ),
  drawerEnableOpenDragGesture: false,
  resizeToAvoidBottomInset: false,
  extendBodyBehindAppBar: true,
)
```

The inner navigator:
```
Navigator(
  key: navigatorKey,
  pages: [
    // This works!
    // const MaterialPage(child: Home())
    
    // This does NOT work as the MaterialPage isn't const
    // MaterialPage(
    //   child: const Home(),
    //   key: ValueKey<MyPage>(HomePage()),
    // )
    
    // This does NOT work as the MaterialPage isn't const
    // I know there is no parameter for the Home() page here, but that is just to keep it simple! That is why I haven't made the Home() or MaterialPage() const as that would not be possible!
    MaterialPage(child: Home())
  ],
  onPopPage: (Route<dynamic> route, dynamic result) {
    if (!route.didPop(result)) {
      return false;
    }

    return true;
  },
)
```

</details>

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue. If there is a crash, please include
      the entirety of the crash log including the backtrace.
-->

```
https://pastebin.com/dYMg4vsL
```

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

These 6 issues can be ignore! They are there because I don't do consts as a proof of concept. The unused imports are just because I have different examples outcommented, so they are needed if testing those.
```
Analyzing navigator_test...                                             

   info • Unused import: 'package:navigator_test/page_model.dart' • lib/inner_router_delegate.dart:2:8 • unused_import
   info • Unused import: 'package:provider/provider.dart' • lib/inner_router_delegate.dart:5:8 • unused_import
   info • Prefer const literals as parameters of constructors on @immutable classes • lib/inner_router_delegate.dart:26:16 • prefer_const_literals_to_create_immutables
   info • Prefer const with constant constructors • lib/inner_router_delegate.dart:35:11 • prefer_const_constructors
   info • Prefer const with constant constructors • lib/inner_router_delegate.dart:35:31 • prefer_const_constructors
   info • The declaration '_convertToMaterialPages' isn't referenced • lib/inner_router_delegate.dart:54:30 • unused_element

6 issues found. (ran in 1.9s)
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[✓] Flutter (Channel stable, 3.3.2, on Ubuntu 22.04.1 LTS 5.15.0-48-generic, locale en_US.UTF-8)
    • Flutter version 3.3.2 on channel stable at /home/rke/snap/flutter/common/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision e3c29ec00c (12 days ago), 2022-09-14 08:46:55 -0500
    • Engine revision a4ff2c53d8
    • Dart version 2.18.1
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /home/rke/Android/Sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /home/rke/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
    • cmake version 3.10.2
    • ninja version 1.8.2
    • pkg-config version 0.29.1

[✓] Android Studio (version 2021.2)
    • Android Studio at /home/rke/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
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] VS Code
    • VS Code at /snap/code/current
    • Flutter extension version 3.48.0

[✓] Connected device (3 available)
    • Pixel 3a (mobile) • 94HAY0P9L3 • android-arm64  • Android 12 (API 32)
    • Linux (desktop)   • linux      • linux-x64      • Ubuntu 22.04.1 LTS 5.15.0-48-generic
    • Chrome (web)      • chrome     • web-javascript • Google Chrome 105.0.5195.125

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
```

</details>


<!--
      Consider also attaching screenshots and/or videos to better
      illustrate the issue.

      You can upload them directly on GitHub.
      Beware that video file size is limited to 10MB.
-->