路由采用的go-router路由框架:
final rootNavigatorKey = GlobalKey();
final GoRouter routerGlobal = GoRouter(
errorBuilder: (context, state) {
return const ErrorPage();
},
navigatorKey: rootNavigatorKey,
routes: [
GoRoute(
path: '/',
name: "login",
parentNavigatorKey: rootNavigatorKey,
builder: (BuildContext context, GoRouterState state) {
return const LoginPage();
}),
//......省略部分路由
GoRoute(
path: '/error',
name: "error",
parentNavigatorKey: rootNavigatorKey,
builder: (BuildContext context, GoRouterState state) {
return const ErrorPage();
}),
],
);
首先在runApp(MyApp())前添加以下代码:
需要导入dart:html包,由于只能在web中使用,跨平台可以使用universal_html: ^1.2.1代替
if (kIsWeb) {
// 清空浏览器历史记录
html.window.history.replaceState(null, "", html.window.location.href);
// 禁止后退功能
html.window.onPopState.listen((event) {
html.window.history.pushState(null, "", html.window.location.href);
});
}
添加上面代码后,经过测试还是会后退一步,每当打开一个新的路由后需要再次调用下面代码:
GoRouter.of(context).go(menu.location!);
if (kIsWeb) {
html.window.history.replaceState(null, "", "#$location");
}