Dart Uri()
Syntax & Examples
Uri constructor
The `Uri` class in Dart is used to represent and manipulate URIs (Uniform Resource Identifiers). It provides methods to create, parse, and manipulate URI components.
Syntax of Uri
The syntax of Uri.Uri constructor is:
Uri({String scheme String userInfo String host int port, String path Iterable<String> pathSegments, String query Map<String, dynamic> queryParameters, String fragment })This Uri constructor of Uri creates a new URI from its components.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
scheme | optional | The scheme part of the URI. |
userInfo | optional | The user information part of the URI. |
host | optional | The host part of the URI. |
port | optional | The port part of the URI. |
path | optional | The path part of the URI. |
pathSegments | optional | The path segments of the URI as an iterable of strings. |
query | optional | The query parameters of the URI as a map of key-value pairs. |
fragment | optional | The fragment part of the URI. |
✐ Examples
1 Creating a URI with HTTPS scheme and query parameters
In this example,
- We create a `Uri` object with HTTPS scheme, host 'example.com', path '/path/to/resource', query parameters 'param1=value1' and 'param2=value2', and fragment 'section'.
- We print the URI to standard output.
Dart Program
void main() {
Uri uri = Uri(
scheme: 'https',
host: 'example.com',
path: '/path/to/resource',
queryParameters: {'param1': 'value1', 'param2': 'value2'},
fragment: 'section'
);
print(uri);
}Output
https://example.com/path/to/resource?param1=value1¶m2=value2#section
2 Creating a URI with FTP scheme, user info, and path segments
In this example,
- We create a `Uri` object with FTP scheme, user info 'user:password', host 'example.com', port 21, path segments 'path', 'to', and 'file', query 'query=example', and fragment 'section'.
- We print the URI to standard output.
Dart Program
void main() {
Uri uri = Uri(
scheme: 'ftp',
userInfo: 'user:password',
host: 'example.com',
port: 21,
pathSegments: ['path', 'to', 'file'],
query: 'query=example',
fragment: 'section'
);
print(uri);
}Output
ftp://user:password@example.com/path/to/file?query=example#section
3 Creating a mailto URI
In this example,
- We create a `Uri` object with 'mailto' scheme and 'email@example.com' as the path.
- We print the URI to standard output.
Dart Program
void main() {
Uri uri = Uri(
scheme: 'mailto',
path: 'email@example.com',
);
print(uri);
}Output
mailto:email@example.com
Summary
In this Dart tutorial, we learned about Uri constructor of Uri: the syntax and few working examples with output and detailed explanation for each example.