Repository: flutter
Issue: App shows a blank page when there is an exception in appState (Using go_router and Riverpod)
Labels: package,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.24,found in release: 3.25

### What package does this bug report belong to?

go_router

### What target platforms are you seeing this bug on?

Android, Web, Windows

### 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: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
      url: "https://pub.dev"
    source: hosted
    version: "1.18.0"
  cupertino_icons:
    dependency: "direct main"
    description:
      name: cupertino_icons
      sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
      url: "https://pub.dev"
    source: hosted
    version: "1.0.8"
  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: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c"
      url: "https://pub.dev"
    source: hosted
    version: "4.0.0"
  flutter_riverpod:
    dependency: "direct main"
    description:
      name: flutter_riverpod
      sha256: "0f1974eff5bbe774bf1d870e406fc6f29e3d6f1c46bd9c58e7172ff68a785d7d"
      url: "https://pub.dev"
    source: hosted
    version: "2.5.1"
  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: ddc16d34b0d74cb313986918c0f0885a7ba2fc24d8fb8419de75f0015144ccfe
      url: "https://pub.dev"
    source: hosted
    version: "14.2.3"
  leak_tracker:
    dependency: transitive
    description:
      name: leak_tracker
      sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05"
      url: "https://pub.dev"
    source: hosted
    version: "10.0.5"
  leak_tracker_flutter_testing:
    dependency: transitive
    description:
      name: leak_tracker_flutter_testing
      sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806"
      url: "https://pub.dev"
    source: hosted
    version: "3.0.5"
  leak_tracker_testing:
    dependency: transitive
    description:
      name: leak_tracker_testing
      sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
      url: "https://pub.dev"
    source: hosted
    version: "3.0.1"
  lints:
    dependency: transitive
    description:
      name: lints
      sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235"
      url: "https://pub.dev"
    source: hosted
    version: "4.0.0"
  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: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb
      url: "https://pub.dev"
    source: hosted
    version: "0.12.16+1"
  material_color_utilities:
    dependency: transitive
    description:
      name: material_color_utilities
      sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
      url: "https://pub.dev"
    source: hosted
    version: "0.11.1"
  meta:
    dependency: transitive
    description:
      name: meta
      sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7
      url: "https://pub.dev"
    source: hosted
    version: "1.15.0"
  path:
    dependency: transitive
    description:
      name: path
      sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af"
      url: "https://pub.dev"
    source: hosted
    version: "1.9.0"
  riverpod:
    dependency: transitive
    description:
      name: riverpod
      sha256: f21b32ffd26a36555e501b04f4a5dca43ed59e16343f1a30c13632b2351dfa4d
      url: "https://pub.dev"
    source: hosted
    version: "2.5.1"
  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: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
      url: "https://pub.dev"
    source: hosted
    version: "1.11.1"
  state_notifier:
    dependency: transitive
    description:
      name: state_notifier
      sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb
      url: "https://pub.dev"
    source: hosted
    version: "1.0.0"
  stream_channel:
    dependency: transitive
    description:
      name: stream_channel
      sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
      url: "https://pub.dev"
    source: hosted
    version: "2.1.2"
  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: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb"
      url: "https://pub.dev"
    source: hosted
    version: "0.7.2"
  vector_math:
    dependency: transitive
    description:
      name: vector_math
      sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
      url: "https://pub.dev"
    source: hosted
    version: "2.1.4"
  vm_service:
    dependency: transitive
    description:
      name: vm_service
      sha256: f652077d0bdf60abe4c1f6377448e8655008eef28f128bc023f7b5e8dfeb48fc
      url: "https://pub.dev"
    source: hosted
    version: "14.2.4"
sdks:
  dart: ">=3.5.0 <4.0.0"
  flutter: ">=3.18.0-18.0.pre.54"

```

</details>


### Steps to reproduce

```
Here are the steps to reproduce the "Duplicate GlobalKey detected in widget tree" error in the provided Flutter app:

Run the App:

Launch the Flutter app by running the main.dart file.
Login to the App:

On the LoginPage, click the Login button to authenticate. This will redirect you to the HomePage.
Navigate to Settings Page:

Use the bottom navigation bar to switch to the Settings page.
Trigger the Error:

On the SettingsPage, click the Log Out That Throws Exception button.
Observe the Error:

The error will be thrown with a message indicating a "Duplicate GlobalKey detected in the widget tree." This error occurs due to the GlobalKey being reused improperly when the state is not correctly managed after the exception is thrown during sign-out.
These steps should consistently reproduce the error.
```
Here is a full repo link for detailed analysis: https://github.com/Zia-Ch/test_project



### Expected results

I am using Riverpod as state management and go_router for routing.
I have two pages three pages one is Login, second is Home and third is Settings.
Home and Settings are being displayed with a bottom nav bar.
after login my app directs to the main dashboard called as mainPage in my app.
And on settings page there are two button on is normal signOut but the other throws an exception (to reproduce the same effect as I faced). 
When this exception is thrown app shows a blank page and throws an error as mentioned in actual results section.

### My Expected Results are:
App Should not Log Out and must remain on the same page without showing any changes.

### Actual results

Upon clicking on 'Logout that throws exception' Button, app shows a blank page along with bottom nav bar and shows an error as listed below:


```
FlutterError (Duplicate GlobalKey detected in widget tree.
The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [GlobalObjectKey int#62661]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- KeyedSubtree-[GlobalKey#d6f1a]
A GlobalKey can only be specified on one widget at a time in the widget tree.)
```

### Code sample

<details open><summary>Code sample</summary>

```dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

void main() {
  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final router = ref.watch(routeProvider);
    return MaterialApp.router(
      title: 'Flutter Test',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      routerConfig: router,
    );
  }
}

final GlobalKey<NavigatorState> _rootNavigatorKey =
    GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellNavigatorKey =
    GlobalKey<NavigatorState>(debugLabel: 'shell');

final routeProvider = Provider((ref) {
  final authState = ref.watch(authStateProvider);

  return GoRouter(
    navigatorKey: _rootNavigatorKey,
    debugLogDiagnostics: true,
    initialLocation: '/',
    routes: <RouteBase>[
      ShellRoute(
        navigatorKey: _shellNavigatorKey,
        builder: (context, state, child) => MainPage(
          body: child,
        ),
        routes: <RouteBase>[
          GoRoute(
            path: AppPages.home.toPath,
            name: AppPages.home.name,
            builder: (context, state) {
              return const HomePage();
            },
          ),
          GoRoute(
            path: AppPages.settings.toPath,
            name: AppPages.settings.name,
            builder: (context, state) {
              return const SettingsPage();
            },
          ),
        ],
      ),
      GoRoute(
        path: AppPages.login.toPath,
        name: AppPages.login.name,
        builder: (context, state) => const LoginPage(),
      ),
    ],
    redirect: (context, state) {
      final authenticated = authState.status == AuthStatus.authenticated;
      if (!authenticated) {
        return AppPages.login.toPath;
      }

      return null;
    },
  );
});

enum AppPages {
  home(0),
  settings(1),
  login(2);

  final int value;
  const AppPages(this.value);
}

extension AppPagesX on int {
  AppPages get toAppPage {
    switch (this) {
      case 0:
        return AppPages.home;
      case 1:
        return AppPages.settings;
      case 2:
        return AppPages.login;
      default:
        return AppPages.home;
    }
  }
}

extension XPath on AppPages {
  String get toPath {
    switch (this) {
      case AppPages.home:
        return '/';
      case AppPages.settings:
        return '/settings';
      case AppPages.login:
        return '/login';
      default:
        return '/';
    }
  }
}

enum AuthStatus {
  initial,
  authenticated,
  unathenticated,
}

class AuthState {
  final AuthStatus status;
  final String? errorMessage;
  final String message;

  AuthState({
    required this.status,
    this.errorMessage,
    this.message = '',
  });

  factory AuthState.initial() {
    return AuthState(
      status: AuthStatus.initial,
      message: 'Initial',
      errorMessage: null,
    );
  }

  factory AuthState.authenticated() {
    return AuthState(
      status: AuthStatus.authenticated,
      message: 'Authenticated',
      errorMessage: null,
    );
  }

  factory AuthState.unathenticated() {
    return AuthState(
      status: AuthStatus.unathenticated,
      message: 'Unauthenticated',
      errorMessage: 'Something went wrong',
    );
  }

  AuthState copyWith({
    AuthStatus? status,
    String? errorMessage,
    String? message,
  }) {
    return AuthState(
      status: status ?? this.status,
      errorMessage: errorMessage,
      message: message ?? this.message,
    );
  }
}

final authStateProvider =
    StateNotifierProvider<AuthStateController, AuthState>((ref) {
  return AuthStateController();
});

class AuthStateController extends StateNotifier<AuthState> {
  AuthStateController() : super(AuthState.initial());
  final AuthRepository _authRepository = AuthRepository();

  void signIn() async {
    await _authRepository.signIn();
    state = AuthState.authenticated();
  }

  void signOut() async {
    await _authRepository.signOut();
    state = AuthState.unathenticated();
  }

  void signOutThrowsException() async {
    try {
      await _authRepository.signOutThrowsException();
    } catch (_) {
      state = state.copyWith(
        status: AuthStatus.authenticated,
        errorMessage: 'Something went wrong',
        message: 'stillAuthenticated',
      );
    }
  }
}

class AuthRepository {
  AuthRepository();

  Future<bool> signIn() async {
    return true;
  }

  Future<bool> signOut() async {
    return true;
  }

  Future<bool> signOutThrowsException() {
    try {
      throw Exception('Something went wrong');
    } catch (_) {
      throw Exception('Something went wrong');
    }
  }
}

final selectedPageProvider = StateProvider<AppPages>((ref) {
  return AppPages.home;
});

class MainPage extends ConsumerWidget {
  const MainPage({required this.body, super.key});
  final Widget body;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final page = ref.watch(selectedPageProvider);
    return Scaffold(
      body: body,
      bottomNavigationBar: NavigationBar(
        onDestinationSelected: (value) {
          final page = value.toAppPage;
          ref.read(selectedPageProvider.notifier).state = page;
          context.go(page.toPath);
        },
        selectedIndex: page.index,
        destinations: destinations,
      ),
    );
  }
}

List<NavigationDestination> destinations = const [
  NavigationDestination(icon: Icon(Icons.home), label: "Home"),
  NavigationDestination(icon: Icon(Icons.settings), label: "Settings"),
];

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text('Home'),
      ),
    );
  }
}

class SettingsPage extends ConsumerWidget {
  const SettingsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Settings'),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                ref.read(authStateProvider.notifier).signOut();
              },
              child: const Text("Simple Logout"),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                ref.read(authStateProvider.notifier).signOutThrowsException();
              },
              child: const Text('Log Out That Throws Exception'),
            ),
          ],
        ),
      ),
    );
  }
}

class LoginPage extends ConsumerWidget {
  const LoginPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            ref.read(authStateProvider.notifier).signIn();
          },
          child: const Text("Login"),
        ),
      ),
    );
  }
}

```

</details>


### Screenshots or Videos

<details open>
<summary>Screenshots / Video demonstration</summary>


https://github.com/user-attachments/assets/994b5b29-027c-4eb7-81c5-f4c065d6e237


</details>


### Logs

<details open><summary>Logs</summary>

```console
[Paste your logs here]
```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.24.0, on Microsoft Windows [Version 10.0.22621.4037], locale en-PK)
[✓] Windows Version (Installed version of Windows is version 10 or higher)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Chrome - develop for the web
[✓] Visual Studio - develop Windows apps (Visual Studio Build Tools 2022 17.6.5)
[✓] Android Studio (version 2022.2)
[✓] VS Code (version 1.92.2)
[✓] Connected device (3 available)
[✓] Network resources

• No issues found!
```

</details>