You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web中使用GoRouter获取URL哈希#后的数值问题

解决GoRouter中获取URL哈希值的问题

当你使用PathUrlStrategy时,GoRouter默认会剥离URL中的哈希部分——毕竟这个策略的设计初衷就是移除传统SPA依赖的#路由模式。要拿到#后的数值,可以试试下面两种方法:

方法一:直接从浏览器对象获取

在Flutter Web环境里,能直接访问浏览器的window.location.hash拿到完整哈希串,再去掉开头的#就行:

import 'dart:html' as html;

// 在需要的地方调用这段代码
String hashValue = html.window.location.hash.replaceFirst('#', '');
// 此时hashValue的值就是你要的'someValue'

方法二:自定义UrlStrategy保留哈希

如果希望GoRouter的state对象能直接读取到哈希值,可以自定义一个UrlStrategy,在处理路径时保留哈希部分:

import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:go_router/go_router.dart';
import 'dart:html' as html;

class HashPreservingPathUrlStrategy extends PathUrlStrategy {
  @override
  String prepareExternalUrl(String internalUrl) {
    final hash = html.window.location.hash;
    return super.prepareExternalUrl(internalUrl) + hash;
  }

  @override
  String getPath() {
    final path = super.getPath();
    final hash = html.window.location.hash;
    return path + hash;
  }
}

// 初始化时替换默认策略
void main() {
  setUrlStrategy(HashPreservingPathUrlStrategy());
  runApp(const MyApp());
}

之后在GoRoute的pageBuilder里,state.fullPath就会包含完整的/path#someValue,再通过字符串处理提取哈希:

GoRoute(
  path: '/path',
  pageBuilder: (context, state) {
    final fullPath = state.fullPath ?? '';
    final hashIndex = fullPath.indexOf('#');
    String hashValue = '';
    if (hashIndex != -1) {
      hashValue = fullPath.substring(hashIndex + 1);
    }
    // 这里hashValue就是目标值'someValue'
    return MaterialPage(child: PathPage(hash: hashValue));
  },
)

两种方法各有适用场景:第一种简单直接,适合只需要单次获取哈希的场景;第二种适合需要在GoRouter的路由逻辑中统一处理哈希的场景,但要注意和现有路由规则兼容,避免冲突。

内容的提问来源于stack exchange,提问作者Tom Raganowicz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:03:12