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

Flutter Web中如何通过go_router获取域名与完整路径?

Flutter Web 获取子域名与完整路径方案

因为GoRouterState仅提供路径信息,无法直接获取域名/子域名,你可以通过Flutter Web对浏览器API的直接访问来实现需求:

  • 核心思路:利用dart:html库调用浏览器的window.location对象,获取主机名(含子域名)和路径信息,再拼接成目标格式。

实现步骤

  1. 导入依赖包
    引入Web环境相关的库,同时加入Web环境判断避免非Web端报错:

    import 'dart:html' as html;
    import 'package:flutter/foundation.dart';
    
  2. 封装获取函数
    写一个工具函数,统一处理域名和路径的拼接:

    String getFullDomainAndPath() {
      if (!kIsWeb) return ''; // 非Web环境可根据需求返回默认值或抛出异常
      // 获取含子域名的主机名(如 "sub.domain.com",若有端口则包含端口)
      final host = html.window.location.host;
      // 获取路径(如 "/path")
      final path = html.window.location.pathname;
      // 拼接成目标格式
      return '$host$path';
    }
    

    若不需要端口号,可改用html.window.location.hostname替代host,只获取纯主机名。

  3. 结合GoRouter使用
    在GoRouter的路由页面或回调中直接调用该函数即可:

    final router = GoRouter(
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) {
            final fullAddress = getFullDomainAndPath();
            // 将完整地址传递给页面使用
            return HomePage(fullAddress: fullAddress);
          },
        ),
        // 其他路由同理
      ],
    );
    

注意事项

  • 该方案仅适用于Web环境,非Web端需做兼容处理;
  • 如果需要在路由守卫(如redirect)中使用,同样可以直接调用getFullDomainAndPath()函数获取信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:40:05