Flutter Web:如何在Dart代码中获取base_href?
在Flutter Web的Dart代码中获取base-href配置路径
首先明确base-href的两种配置方式:
- 构建命令配置:执行
flutter build web --base-href "/path/" - 静态文件配置:在项目的
index.html中添加<base href="/path/">
当配置--base-href "/foo/"后,访问URL为http://localhost:8080/foo/some-route时,直接使用Uri.base.path会返回完整的/foo/some-route,但我们需要单独提取出配置的/foo/路径,这里有个可靠的实现方式:
直接读取HTML中的<base>标签属性,因为不管是通过构建命令还是手动修改index.html配置的base-href,最终都会在页面的DOM中生成这个标签。
仅Web环境实现代码
import 'dart:html'; String getBaseHref() { final baseElement = document.querySelector('base'); // 从完整href中截取域名后的路径部分,比如将http://localhost:8080/foo/处理为/foo/ return baseElement?.href.split(window.location.origin).last ?? '/'; }
注:直接取
baseElement?.href会返回带域名的完整URL,因此需要用window.location.origin截取掉域名部分,得到纯路径。
跨平台兼容代码
如果你的项目是跨平台的,为避免非Web环境报错,可添加平台判断:
import 'dart:html' as html; import 'package:flutter/foundation.dart'; String getBaseHref() { if (!kIsWeb) return '/'; final baseElement = html.document.querySelector('base'); if (baseElement?.href == null) return '/'; return baseElement!.href.split(html.window.location.origin).last; }
内容的提问来源于stack exchange,提问作者ozraru
相关产品推荐
相关产品推荐

