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

ParameterOptional/RequiredDescription
schemeoptionalThe scheme part of the URI.
userInfooptionalThe user information part of the URI.
hostoptionalThe host part of the URI.
portoptionalThe port part of the URI.
pathoptionalThe path part of the URI.
pathSegmentsoptionalThe path segments of the URI as an iterable of strings.
queryoptionalThe query parameters of the URI as a map of key-value pairs.
fragmentoptionalThe fragment part of the URI.


✐ Examples

1 Creating a URI with HTTPS scheme and query parameters

In this example,

  1. 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'.
  2. 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&param2=value2#section

2 Creating a URI with FTP scheme, user info, and path segments

In this example,

  1. 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'.
  2. 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,

  1. We create a `Uri` object with 'mailto' scheme and 'email@example.com' as the path.
  2. 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.