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

使用Uri.http()时无法正确编码加号(+)符号的问题求助

问题:Uri.http()无法正确编码包含加号的参数字符串

当使用Uri.http()创建Uri获取数据时,若参数字符串包含加号(+),加号无法被正确编码为%2B;但将该字符串直接硬编码到参数Map中时,加号会被成功编码。

代码示例

// widget.param的值为: pA7+pWPaPSZUw5VKimKVlzA3mKrg=
final getFromUri = Uri.http(
  widget.config,
  'invoiceTracking',
  {'tracking': widget.param},
  // 硬编码参数的写法 {'tracking': 'pA7+pWPaPSZUw5VKimKVlzA3mKrg='},
);

编码结果对比

  • 使用变量传递参数时,发送的内容为:"pA7+pWPaPSZUw5VKimKVlzA3mKrg%3D"(加号未被编码)
  • 硬编码参数时,发送的内容为:"pA7%2BpWPaPSZUw5VKimKVlzA3mKrg%3D"(加号被正确编码为%2B)

解决方案

原因

Uri.http()内部默认使用Uri.encodeQueryComponent()处理参数,该方法遵循application/x-www-form-urlencoded规则,会将+视为空格的替代符号,因此不会对其进行编码;而硬编码字符串时,Dart的Uri解析逻辑会将+当作普通字符处理,自动编码为%2B。

解决方法

手动使用Uri.encodeComponent()对参数值进行编码,再传入参数Map中:

// 先手动编码包含加号的参数值
final encodedParam = Uri.encodeComponent(widget.param);
final getFromUri = Uri.http(
  widget.config,
  'invoiceTracking',
  {'tracking': encodedParam},
);

这样处理后,参数中的+会被正确编码为%2B,同时等号(=)也会被正常编码为%3D,符合预期的URI编码规则。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:40:21