前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

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

路由采用的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");
   }                     

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

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言