Divyam Makar
Divyam Makar

Reputation: 106

"Cannot set URL strategy more than once." error using go_router with Flutter Web

I am using go_router flutter package for Flutter Web. I am getting this error while reloading the website. The back button is working great but the reload causes this.

Assertion failed: org-dartlang-sdk:///flutter_web_sdk/lib/_engine/engine/window.dart:25:10 !_isUrlStrategySet "Cannot set URL strategy more than once."

Below is the code for my main.dart:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:navigator_2/some_app.dart';

import 'details_page.dart';

void main() {
runApp( MyApp());
}


class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
  final GoRouter _router = GoRouter(
    urlPathStrategy: UrlPathStrategy.path,
    routes: [
  GoRoute(path: '/',builder: (context,state)=> const SomeAppPage()),
  GoRoute(path: '/details',builder: (context,state){
    final query = state.queryParams['index'];
    return DetailsPage(index: int.parse(query!));
  }),
]);
return  MaterialApp.router(
  routeInformationParser: _router.routeInformationParser,
    routerDelegate: _router.routerDelegate ,
    title: 'Go Router Example',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
);
 }
 }

Upvotes: 4

Views: 5264

Answers (3)

Zelf
Zelf

Reputation: 2250

The url path strategy to remove the # character from url's should be set in main().

As of go_router 5.1.0, urlPathStrategy has been completely removed, so GoRouter.setUrlPathStrategy(UrlPathStrategy.path); would cause a build error.

In the 5.0 migration guide, instead of GoRouter.setUrlPathStrategy(UrlPathStrategy.path); replace with:

import 'package:flutter_web_plugins/url_strategy.dart';

void main() {
  usePathUrlStrategy();
  runApp(ExampleApp());
}

Upvotes: 10

RobertoAllende
RobertoAllende

Reputation: 9508

Divyam Makar's answer didn't work for me because I need to use ChangeNotifier subclass on my GoRouter definition, so when I moved the GoRouter initialisation to initState, I got the exception:

dependOnInheritedWidgetOfExactType<_InheritedProviderScope<MyCustomState?>>() or dependOnInheritedElement() was called before _MainWidgetState.initState() completed.

So, following the documentation, I set the Url Path Strategy in an upper level of the hierarchy, in the main method:

void main() {
  GoRouter.setUrlPathStrategy(UrlPathStrategy.path);
  runApp(App());
}

Upvotes: 2

Divyam Makar
Divyam Makar

Reputation: 106

I got the answer. It was just that because GoRouter was defined in build function then during reload its called again and thus causing this error. Removing it and putting it in initState solves it.

Upvotes: 0

Related Questions