专业的编程技术博客社区

网站首页 > 博客文章 正文

Flutter web开发中禁用浏览器后退按钮

baijin 2025-05-23 15:13:54 博客文章 3 ℃ 0 评论

路由采用的go-router路由框架:

final rootNavigatorKey = GlobalKey<NavigatorState>();
final GoRouter routerGlobal = GoRouter(
  errorBuilder: (context, state) {
    return const ErrorPage();
  },
  navigatorKey: rootNavigatorKey,
  routes: <RouteBase>[
    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");
   }                     

当点击浏览器后退按钮时,地址栏地址将不再发生变化:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表