📜  flutter await uri - Dart (1)

📅  最后修改于: 2023-12-03 15:15:07.153000             🧑  作者: Mango

Flutter中使用await Uri

在Flutter中,我们可以使用await Uri来处理URI(Uniform Resource Identifier)相关的操作,包括解析、拼接、查询参数等等。下面就来介绍一下await Uri的用法。

解析URI

在Flutter中,我们可以使用Uri.parse()函数来解析URI字符串,如下所示:

Uri uri = Uri.parse('https://example.com/path');
print(uri); // 输出:https://example.com/path

Uri.parse()函数返回一个Uri对象,该对象包含了解析后的URI信息,如协议、主机、路径等等。

URI拼接

拼接URI可以使用Uri.https()Uri.http()函数,在HTTP协议中使用Uri.http()函数,在HTTPS协议中使用Uri.https()函数。这两个函数均接受三个参数:主机名、路径和查询参数。如下所示:

Uri uri = Uri.https('example.com', '/path', {'query': 'param'});
print(uri); // 输出:https://example.com/path?query=param

在上面的示例中,我们使用Uri.https()函数将主机名、路径和查询参数拼接成一个URI字符串。

获取URI的各个部分

Uri对象还有很多其他方法,可用于获取URI的各个部分,如:

  • uri.scheme:获取协议
  • uri.host:获取主机名
  • uri.port:获取端口号,如果没有则返回默认端口
  • uri.path:获取路径
  • uri.query:获取查询参数
  • uri.fragment:获取锚点

以下是示例代码:

Uri uri = Uri.parse('https://example.com/path?query=param#fragment');
print(uri.scheme); // 输出:https
print(uri.host); // 输出:example.com
print(uri.port); // 输出:443
print(uri.path); // 输出:/path
print(uri.query); // 输出:query=param
print(uri.fragment); // 输出:fragment
注意事项
  • 如果URI中包含非法字符,如空格\"等等,可使用函数Uri.encodeFull()Uri.encodeComponent()对其进行编码。
  • 获取uri.port时,如果URI中没有端口号会默认返回协议对应的端口号。

以上就是在Flutter中使用await Uri的介绍,希望对您有所帮助。