如何在Dart中安全地解析查询字符串?
我们假设我的q字符串值为:
?page=main&action=front&sid=h985jg9034gj498g859gh495
Run Code Online (Sandbox Code Playgroud)
理想情况下,代码应该在服务器和客户端都可以工作,但是现在我将满足于工作的客户端代码.
nun*_*aba 16
越简单越好.查找类Uri 的splitQueryString静态方法.
Map<String, String> splitQueryString(String query, {Encoding encoding: UTF8})
Returns the query split into a map according to the rules specified for
FORM post in the HTML 4.01 specification section 17.13.4. Each key and value
in the returned map has been decoded. If the query is the empty string an
empty map is returned.
Run Code Online (Sandbox Code Playgroud)
我为此目的制作了一个简单的包:https://github.com/kaisellgren/QueryString
例:
import 'package:query_string/query_string.dart');
void main() {
var q = '?page=main&action=front&sid=h985jg9034gj498g859gh495&enc=+Hello%20&empty';
var r = QueryString.parse(q);
print(r['page']); // "main"
print(r['asdasd']); // null
}
Run Code Online (Sandbox Code Playgroud)
结果是Map.访问参数只是一个简单的方法r['action'],访问一个不存在的查询参数是null.
现在,要安装,添加到您pubspec.yaml的依赖项:
dependencies:
query_string: any
Run Code Online (Sandbox Code Playgroud)
并运行pub install.
该库还处理类似%20和的解码,+甚至可以处理空参数.
它不支持"数组样式参数",因为它们不是RFC 3986规范的一部分.