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,
),
);
}
}
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());
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With