Repository: flutter
Issue: [go_router] [Web] Exception thrown when using Gorouter replace: The following GoException was thrown while dispatching notifications for GoRouteInformationProvider: Location cannot be empty.
Labels: platform-web,package,has reproducible steps,P2,p: go_router,team-go_router,triaged-go_router,found in release: 3.19,found in release: 3.20

### Steps to reproduce

1. Go to a sub route of a route
2. Click back button 
3. Exception is thrown, previous screen not built

### Expected results

Navigation works normally

### Actual results

```
══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
The following GoException was thrown while dispatching notifications for GoRouteInformationProvider:
Location cannot be empty.

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:49  throw_
packages/go_router/src/path_utils.dart 125:5                                  canonicalUri
packages/go_router/src/configuration.dart 296:31                              findMatch
packages/go_router/src/match.dart 947:23                                      convert
dart-sdk/lib/convert/codec.dart 30:34                                         decode
packages/go_router/src/parser.dart 71:32                                      parseRouteInformationWithDependencies
packages/flutter/src/widgets/router.dart 743:12                               [_processRouteInformation]
packages/flutter/src/widgets/router.dart 762:5                                [_handleRouteInformationProviderNotification]
packages/flutter/src/foundation/change_notifier.dart 403:24                   notifyListeners
packages/go_router/src/information_provider.dart 134:11                       notifyListeners
packages/go_router/src/information_provider.dart 235:5                        [_platformReportsNewRouteInformation]
packages/go_router/src/information_provider.dart 279:5                        didPushRouteInformation
packages/flutter/src/widgets/binding.dart 704:25                              _handlePushRouteInformation
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50            <fn>
dart-sdk/lib/async/zone.dart 1661:54                                          runUnary
dart-sdk/lib/async/future_impl.dart 156:18                                    handleValue
dart-sdk/lib/async/future_impl.dart 840:44                                    handleValueCallback
dart-sdk/lib/async/future_impl.dart 869:13                                    _propagateToListeners
dart-sdk/lib/async/future_impl.dart 641:5                                     [_completeWithValue]
dart-sdk/lib/async/future_impl.dart 715:7                                     callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:15           <fn>

The GoRouteInformationProvider sending notification was:
  Instance of 'GoRouteInformationProvider'

```

### Code sample

<details open><summary>main.dart</summary>

```dart
import 'package:flutter/material.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:go_router/go_router.dart';
import 'package:testing_textfield/router.dart';

void main() {
  GoRouter.optionURLReflectsImperativeAPIs = true;
  setUrlStrategy(PathUrlStrategy());
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final _router = GoRouter(
    initialLocation: '/',
    routes: $appRoutes,
    debugLogDiagnostics: true,
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'TESTING GO ROUTER',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: const Color.fromARGB(255, 235, 235, 241),
      ),
      routeInformationParser: _router.routeInformationParser,
      routeInformationProvider: _router.routeInformationProvider,
      routerDelegate: _router.routerDelegate,
    );
  }
}
```

</details>

<details open><summary>router.dart</summary>

```dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

part 'router.g.dart';

@TypedGoRoute<HomeRouter>(path: '/')
class HomeRouter extends GoRouteData {
  @override
  Page<void> buildPage(BuildContext context, GoRouterState state) {
    return NoTransitionPage(
        child: Scaffold(
      key: UniqueKey(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('HOME SCREEN'),
            const SizedBox(height: 20),
            InkWell(
              child: const Text('GO TO EVENT SCREEN'),
              onTap: () =>
                  GoRouter.of(context).replace(EventsRouter().location),
            )
          ],
        ),
      ),
    ));
  }
}

@TypedGoRoute<EventsRouter>(
  path: '/events',
  routes: [
    TypedGoRoute<EventDetailRouter>(
      path: 'details/:id',
    ),
  ],
)
class EventsRouter extends GoRouteData {
  @override
  Page<void> buildPage(BuildContext context, GoRouterState state) {
    return NoTransitionPage(
        child: Scaffold(
      key: UniqueKey(),
      body: Center(
        child: InkWell(
          child: const Text('GO TO EVENT ID SCREEN'),
          onTap: () => EventDetailRouter('testing 123 123').go(context),
        ),
      ),
    ));
  }
}

class EventDetailRouter extends GoRouteData {
  EventDetailRouter(this.id);

  final String id;

  @override
  Page<void> buildPage(BuildContext context, GoRouterState state) {
    return NoTransitionPage(
        child: Scaffold(
      key: UniqueKey(),
      body: Center(
        child: Text(id),
      ),
    ));
  }
}

```

</details>

<details open><summary>router.g.dart</summary>

```dart
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'router.dart';

// **************************************************************************
// GoRouterGenerator
// **************************************************************************

List<RouteBase> get $appRoutes => [
      $homeRouter,
      $eventsRouter,
    ];

RouteBase get $homeRouter => GoRouteData.$route(
      path: '/',
      factory: $HomeRouterExtension._fromState,
    );

extension $HomeRouterExtension on HomeRouter {
  static HomeRouter _fromState(GoRouterState state) => HomeRouter();

  String get location => GoRouteData.$location(
        '/',
      );

  void go(BuildContext context) => context.go(location);

  Future<T?> push<T>(BuildContext context) => context.push<T>(location);

  void pushReplacement(BuildContext context) =>
      context.pushReplacement(location);

  void replace(BuildContext context) => context.replace(location);
}

RouteBase get $eventsRouter => GoRouteData.$route(
      path: '/events',
      factory: $EventsRouterExtension._fromState,
      routes: [
        GoRouteData.$route(
          path: 'details/:id',
          factory: $EventDetailRouterExtension._fromState,
        ),
      ],
    );

extension $EventsRouterExtension on EventsRouter {
  static EventsRouter _fromState(GoRouterState state) => EventsRouter();

  String get location => GoRouteData.$location(
        '/events',
      );

  void go(BuildContext context) => context.go(location);

  Future<T?> push<T>(BuildContext context) => context.push<T>(location);

  void pushReplacement(BuildContext context) =>
      context.pushReplacement(location);

  void replace(BuildContext context) => context.replace(location);
}

extension $EventDetailRouterExtension on EventDetailRouter {
  static EventDetailRouter _fromState(GoRouterState state) => EventDetailRouter(
        state.pathParameters['id']!,
      );

  String get location => GoRouteData.$location(
        '/events/details/${Uri.encodeComponent(id)}',
      );

  void go(BuildContext context) => context.go(location);

  Future<T?> push<T>(BuildContext context) => context.push<T>(location);

  void pushReplacement(BuildContext context) =>
      context.pushReplacement(location);

  void replace(BuildContext context) => context.replace(location);
}


```

</details>



### Screenshots or Video

<details open>
<summary>Screenshots / Video demonstration</summary>


https://github.com/flutter/flutter/assets/51567674/3234158c-63c0-46a2-9093-b03774db6807



</details>


### Logs

<details open><summary>Logs</summary>

```console
Performing hot restart...
Waiting for connection from debug service on Chrome...
Restarted application in 71ms.
The webOnlySetPluginHandler API is deprecated and will be removed in a future release. Please use `setPluginHandler` from `dart:ui_web` instead.
The debugEmulateFlutterTesterEnvironment getter is deprecated and will be removed in a future release. Please use `debugEmulateFlutterTesterEnvironment` from `dart:ui_web` instead.
[GoRouter] Full paths for routes:
  => /
  => /events
  =>   /events/details/:id

[GoRouter] setting initial location /
[GoRouter] replace /events
[GoRouter] going to /events/details/testing%20123%20123
══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
The following GoException was thrown while dispatching notifications for GoRouteInformationProvider:
Location cannot be empty.

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:49  throw_
packages/go_router/src/path_utils.dart 125:5                                  canonicalUri
packages/go_router/src/configuration.dart 296:31                              findMatch
packages/go_router/src/match.dart 947:23                                      convert
dart-sdk/lib/convert/codec.dart 30:34                                         decode
packages/go_router/src/parser.dart 71:32                                      parseRouteInformationWithDependencies
packages/flutter/src/widgets/router.dart 743:12                               [_processRouteInformation]
packages/flutter/src/widgets/router.dart 762:5                                [_handleRouteInformationProviderNotification]
packages/flutter/src/foundation/change_notifier.dart 403:24                   notifyListeners
packages/go_router/src/information_provider.dart 134:11                       notifyListeners
packages/go_router/src/information_provider.dart 235:5                        [_platformReportsNewRouteInformation]
packages/go_router/src/information_provider.dart 279:5                        didPushRouteInformation
packages/flutter/src/widgets/binding.dart 704:25                              _handlePushRouteInformation
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50            <fn>
dart-sdk/lib/async/zone.dart 1661:54                                          runUnary
dart-sdk/lib/async/future_impl.dart 156:18                                    handleValue
dart-sdk/lib/async/future_impl.dart 840:44                                    handleValueCallback
dart-sdk/lib/async/future_impl.dart 869:13                                    _propagateToListeners
dart-sdk/lib/async/future_impl.dart 641:5                                     [_completeWithValue]
dart-sdk/lib/async/future_impl.dart 715:7                                     callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:15           <fn>

The GoRouteInformationProvider sending notification was:
  Instance of 'GoRouteInformationProvider'
════════════════════════════════════════════════════════════════════════════════════════════════════

```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[!] Flutter (Channel [user-branch], 3.13.0, on macOS 12.6.8 21G725 darwin-arm64, locale en-VN)
    ! Flutter version 3.13.0 on channel [user-branch] at /Users/mht/flutter
      Currently on an unknown channel. Run `flutter channel` to switch to an official channel.
      If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.
    ! Upstream repository unknown source is not a standard remote.
      Set environment variable "FLUTTER_GIT_URL" to unknown source to dismiss this error.
    • Framework revision efbf63d9c6 (7 months ago), 2023-08-15 21:05:06 -0500
    • Engine revision 1ac611c64e
    • Dart version 3.1.0
    • DevTools version 2.25.0
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/mht/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/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 11.0.12+0-b1504.28-7817840)

[✓] VS Code (version 1.84.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-arm64   • macOS 12.6.8 21G725 darwin-arm64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 121.0.6167.184

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

```

</details>