[英]"Cannot set URL strategy more than once." error using go_router with Flutter Web
我正在為 Flutter Web 使用 go_router flutter 包。 重新加載網站時出現此錯誤。 后退按鈕效果很好,但重新加載會導致這種情況。
斷言失敗:org-dartlang-sdk:///flutter_web_sdk/lib/_engine/engine/window.dart:25:10 !_isUrlStrategySet “不能多次設置 URL 策略。”
下面是我的 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,
),
);
}
}
我得到了答案。 只是因為 GoRouter 是在構建函數中定義的,然后在重新加載期間再次調用它,從而導致此錯誤。 將其刪除並將其放入 initState 即可解決。
Divyam Makar的回答對我不起作用,因為我需要在我的 GoRouter 定義上使用 ChangeNotifier 子類,所以當我將 GoRouter 初始化移動到 initState 時,我得到了異常:
在 _MainWidgetState.initState() 完成之前調用了dependOnInheritedWidgetOfExactType<_InheritedProviderScope<MyCustomState?>>() 或dependOnInheritedElement()。
因此,按照文檔,我在 main 方法中將 Url Path Strategy 設置在層次結構的上層:
void main() {
GoRouter.setUrlPathStrategy(UrlPathStrategy.path);
runApp(App());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.