Parsing URLs

suggest change

Dart parses, builds and manipulates URLs with the Uri class from dart:core, so you don't need an import or a package. Uri handles:

Uri objects are immutable. Methods like replace return a new Uri.

The examples were run with Dart 3.13.

Parsing a URL into components

Uri.parse takes a string and returns a Uri whose getters return each part of it:

void main() {
  final uri = Uri.parse(
      'https://alice:secret@Example.COM:8443/docs/guide/intro.html?lang=en&v=2#install');

  print('scheme:    ${uri.scheme}');
  print('userInfo:  ${uri.userInfo}');
  print('host:      ${uri.host}');
  print('port:      ${uri.port}');
  print('authority: ${uri.authority}');
  print('path:      ${uri.path}');
  print('segments:  ${uri.pathSegments}');
  print('query:     ${uri.query}');
  print('params:    ${uri.queryParameters}');
  print('fragment:  ${uri.fragment}');
  print('origin:    ${uri.origin}');
  print('absolute:  ${uri.isAbsolute}');
  print(uri);
}

Output:

scheme:    https
userInfo:  alice:secret
host:      example.com
port:      8443
authority: alice:secret@example.com:8443
path:      /docs/guide/intro.html
segments:  [docs, guide, intro.html]
query:     lang=en&v=2
params:    {lang: en, v: 2}
fragment:  install
origin:    https://example.com:8443
absolute:  false
https://alice:secret@example.com:8443/docs/guide/intro.html?lang=en&v=2#install

Some details to note:

Ports, empty parts and unusual URIs

There are has... getters for telling "missing" apart from "empty":

void main() {
  final a = Uri.parse('https://example.com/search');
  print('${a.port} hasPort=${a.hasPort}');
  final b = Uri.parse('http://example.com:80/');
  print('${b.port} hasPort=${b.hasPort} $b');
  final c = Uri.parse('ftp://example.com');
  print('${c.port} path="${c.path}" hasEmptyPath=${c.hasEmptyPath}');
  final d = Uri.parse('https://example.com/a/b/');
  print(d.pathSegments);
  final e = Uri.parse('mailto:bob@example.com?subject=Hi');
  print('${e.scheme} | ${e.path} | ${e.host.isEmpty} | ${e.queryParameters}');
  final f = Uri.parse('http://[::1]:8080/status');
  print('host=${f.host} port=${f.port} authority=${f.authority}');
  final g = Uri.parse('urn:isbn:0451450523');
  print('${g.scheme} ${g.path} hasAuthority=${g.hasAuthority}');
  print(Uri.parse('https://example.com/x#top').hasFragment);
  print(Uri.parse('https://example.com/x?').hasQuery);
}

Output:

443 hasPort=false
80 hasPort=false http://example.com/
0 path="" hasEmptyPath=true
[a, b, ]
mailto | bob@example.com | true | {subject: Hi}
host=::1 port=8080 authority=[::1]:8080
urn isbn:0451450523 hasAuthority=false
true
true

Handling invalid input

Uri.parse throws a FormatException for input it can't parse. Uri.tryParse returns null instead, which is usually what you want for user input:

void main() {
  try {
    Uri.parse('http://example.com:abc/');
  } on FormatException catch (e) {
    print('FormatException: ${e.message}');
  }

  for (final s in [
    'http://example.com:abc',
    'http://[::1/',
    'example.com/path',
    'hello world',
    'http://exa mple.com',
  ]) {
    final u = Uri.tryParse(s);
    print('${s.padRight(24)} -> '
        '${u == null ? 'null' : 'scheme="${u.scheme}" host="${u.host}" path="${u.path}"'}');
  }
}

Output:

FormatException: Invalid port
http://example.com:abc   -> null
http://[::1/             -> null
example.com/path         -> scheme="" host="" path="example.com/path"
hello world              -> scheme="" host="" path="hello%20world"
http://exa mple.com      -> scheme="http" host="exa%20mple.com" path=""

The parser is lenient. Almost any string is a valid URI reference: example.com/path parses as a relative path with no host, and characters that aren't allowed, like spaces, get percent-encoded instead of rejected. So a successful parse doesn't mean the string is a usable web address. Validate the parts you depend on:

/// Returns a normalized http(s) URL or null if [input] isn't one.
Uri? parseWebUrl(String input) {
  var text = input.trim();
  if (!text.contains('://')) text = 'https://$text';
  final uri = Uri.tryParse(text);
  if (uri == null) return null;
  if (uri.scheme != 'http' && uri.scheme != 'https') return null;
  if (uri.host.isEmpty || uri.host.contains('%')) return null;
  return uri;
}

void main() {
  for (final s in [
    'https://dart.dev/language',
    '  example.com/a?b=1 ',
    'HTTP://Example.com',
    'ftp://files.example.com/x',
    'http:///no-host',
    'http://exa mple.com',
    'javascript:alert(1)',
    'http://localhost:8080',
  ]) {
    print('${'"$s"'.padRight(30)} -> ${parseWebUrl(s)}');
  }
}

Output:

"https://dart.dev/language"    -> https://dart.dev/language
"  example.com/a?b=1 "         -> https://example.com/a?b=1
"HTTP://Example.com"           -> http://example.com
"ftp://files.example.com/x"    -> null
"http:///no-host"              -> null
"http://exa mple.com"          -> null
"javascript:alert(1)"          -> null
"http://localhost:8080"        -> http://localhost:8080

An allow-list of schemes matters when a user-supplied URL ends up in a link or a redirect. Otherwise javascript: and data: URLs get through.

Reading query parameters

queryParameters returns a Map<String, String> and keeps the last value of a repeated key. queryParametersAll returns a Map<String, List<String>> with every value:

void main() {
  final uri = Uri.parse(
      'https://shop.example.com/search?q=red+shoes&tag=sale&tag=new&size=&empty&city=S%C3%A3o%20Paulo');

  print(uri.queryParameters);
  print(uri.queryParametersAll);

  final q = uri.queryParameters['q'];
  final page = int.tryParse(uri.queryParameters['page'] ?? '') ?? 1;
  final tags = uri.queryParametersAll['tag'] ?? const [];
  print('q="$q" page=$page tags=$tags');
  print(uri.queryParameters.containsKey('empty'));

  try {
    uri.queryParameters['q'] = 'boots';
  } on UnsupportedError catch (e) {
    print('UnsupportedError: ${e.message}');
  }

  print(Uri.splitQueryString('a=1&b=x%26y&c=hello+world'));
}

Output:

{q: red shoes, tag: new, size: , empty: , city: São Paulo}
{q: [red shoes], tag: [sale, new], size: [], empty: [], city: [São Paulo]}
q="red shoes" page=1 tags=[sale, new]
true
UnsupportedError: Cannot modify unmodifiable map
{a: 1, b: x&y, c: hello world}

Values are always strings. Convert them with int.tryParse, bool.tryParse and similar, and supply defaults. Don't trust them. See Type conversion.

Building URLs

Don't concatenate strings to build URLs. Use the Uri constructors, which encode each component by that component's own rules:

void main() {
  final a = Uri.https('api.example.com', '/v1/search', {
    'q': 'dart & flutter',
    'page': '2',
    'tag': ['web', 'cli'],
  });
  print(a);

  final b = Uri.http('localhost:8080', 'users/42');
  print('$b port=${b.port}');

  final c = Uri(
    scheme: 'https',
    userInfo: 'bot',
    host: 'example.com',
    port: 8443,
    pathSegments: ['files', 'my report.pdf', 'a/b'],
    queryParameters: {'download': '1'},
    fragment: 'page=3',
  );
  print(c);
  print(c.pathSegments);

  final d = Uri(scheme: 'https', host: 'example.com', path: '/a b/ü');
  print(d);

  // Every value must be a String or Iterable<String>.
  final limit = 50;
  final e = Uri.https('example.com', '/items', {'limit': '$limit', 'active': true.toString()});
  print(e);
}

Output:

https://api.example.com/v1/search?q=dart+%26+flutter&page=2&tag=web&tag=cli
http://localhost:8080/users/42 port=8080
https://bot@example.com:8443/files/my%20report.pdf/a%2Fb?download=1#page=3
[files, my report.pdf, a/b]
https://example.com/a%20b/%C3%BC
https://example.com/items?limit=50&active=true

The query map is typed Map<String, dynamic>, so passing a non-string value compiles but fails at runtime:

Uri.https('example.com', '/items', {'limit': 50});
// _TypeError: type 'int' is not a subtype of type 'Iterable<dynamic>'

Two more mistakes come from putting a whole URL into one argument:

void main() {
  print(Uri.https('example.com', '/search?q=dart'));
  print(Uri.https('example.com', '/search?q=dart').queryParameters);
  print(Uri.parse('https://example.com').resolve('search?q=dart'));
}

Output:

https://example.com/search%3Fq=dart
{}
https://example.com/search?q=dart

The path argument is only a path, so ? gets encoded as %3F. Likewise Uri.https('example.com/api', '/v1') throws FormatException: Invalid character, because / isn't allowed in a host.

Modifying a URL

replace returns a copy with some components changed. A component you don't pass, or pass as null, stays as it was:

void main() {
  final uri = Uri.parse('https://example.com/products?category=books&page=1#reviews');

  final next = uri.replace(queryParameters: {
    ...uri.queryParameters,
    'page': '2',
  });
  print(next);

  final noPage = uri.replace(
    queryParameters: Map.of(uri.queryParameters)..remove('page'),
  );
  print(noPage);

  print(uri.replace(scheme: 'http', port: 8080, path: '/catalog'));
  print(uri.removeFragment());
  print(uri.replace(query: ''));
  print(uri.replace(queryParameters: {}).hasQuery);

  final added = uri.replace(pathSegments: [...uri.pathSegments, '42', 'images']);
  print(added);
}

Output:

https://example.com/products?category=books&page=2#reviews
https://example.com/products?category=books#reviews
http://example.com:8080/catalog?category=books&page=1#reviews
https://example.com/products?category=books&page=1
https://example.com/products?#reviews
true
https://example.com/products/42/images?category=books&page=1#reviews

Spreading uri.queryParameters into a new map literal is the idiomatic way to add or override one parameter. This drops repeated keys, so start from queryParametersAll when they matter.

There's removeFragment(), but no removeQuery(). An empty query leaves a dangling ?. To drop the query completely, build a new Uri from the remaining parts:

final noQuery = Uri(
  scheme: uri.scheme,
  userInfo: uri.userInfo,
  host: uri.host,
  port: uri.hasPort ? uri.port : null,
  path: uri.path,
  fragment: uri.hasFragment ? uri.fragment : null,
);
// https://example.com/products#reviews

Resolving relative URLs

resolve follows the RFC 3986 rules for combining a base URL with a relative reference. Browsers use the same rules for links in a page, which makes resolve the right tool for turning href values into absolute URLs when you crawl a site (see Web scraping):

void main() {
  final base = Uri.parse('https://example.com/docs/guide/intro.html?x=1');

  for (final ref in [
    'setup.html',
    './setup.html',
    '../api/index.html',
    '/about',
    '?lang=pl',
    '#section-2',
    '//cdn.example.net/app.js',
    'https://other.org/',
    '',
  ]) {
    print('${'"$ref"'.padRight(28)} -> ${base.resolve(ref)}');
  }

  final api = Uri.parse('https://api.example.com/v1');
  print(api.resolve('users'));
  final api2 = Uri.parse('https://api.example.com/v1/');
  print(api2.resolve('users'));
  print(api2.resolve('/users'));
}

Output:

"setup.html"                 -> https://example.com/docs/guide/setup.html
"./setup.html"               -> https://example.com/docs/guide/setup.html
"../api/index.html"          -> https://example.com/docs/api/index.html
"/about"                     -> https://example.com/about
"?lang=pl"                   -> https://example.com/docs/guide/intro.html?lang=pl
"#section-2"                 -> https://example.com/docs/guide/intro.html?x=1#section-2
"//cdn.example.net/app.js"   -> https://cdn.example.net/app.js
"https://other.org/"         -> https://other.org/
""                           -> https://example.com/docs/guide/intro.html?x=1
https://api.example.com/users
https://api.example.com/v1/users
https://api.example.com/users

The last three lines show the most common bug with API base URLs. A relative reference replaces the last segment of the base path, so v1 is dropped unless the base ends with /. A reference that starts with / always replaces the whole path. Give a base URL a trailing slash and resolve relative paths against it, or build the path with replace(pathSegments: [...base.pathSegments, 'users']).

resolveUri(Uri) does the same thing for a reference that is already a Uri. Uri.parse also removes . and .. segments from absolute paths, so https://example.com/a/./b/../c/ comes back as https://example.com/a/c/.

Encoding and decoding components

When you only have a piece of a URL, the static helpers encode and decode it:

void main() {
  const s = 'a b&c=d/e?f#g+h~ł';

  print('encodeComponent:      ${Uri.encodeComponent(s)}');
  print('encodeQueryComponent: ${Uri.encodeQueryComponent(s)}');
  print('encodeFull:           ${Uri.encodeFull('https://example.com/a b?q=x y&z=ł')}');

  print(Uri.decodeComponent('a%20b%26c+d'));
  print(Uri.decodeQueryComponent('a%20b%26c+d'));
  print(Uri.decodeFull('https://example.com/a%20b?q=%C5%82'));

  final name = 'Tom & Jerry';
  final bad = Uri.parse('https://example.com/search?q=$name');
  final good = Uri.parse('https://example.com/search?q=${Uri.encodeQueryComponent(name)}');
  print('${bad.queryParameters}  vs  ${good.queryParameters}');

  try {
    Uri.decodeComponent('100%');
  } on ArgumentError catch (e) {
    print('ArgumentError: ${e.message}');
  }
}

Output:

encodeComponent:      a%20b%26c%3Dd%2Fe%3Ff%23g%2Bh~%C5%82
encodeQueryComponent: a+b%26c%3Dd%2Fe%3Ff%23g%2Bh~%C5%82
encodeFull:           https://example.com/a%20b?q=x%20y&z=%C5%82
a b&c+d
a b&c d
https://example.com/a b?q=ł
{q: Tom ,  Jerry: }  vs  {q: Tom & Jerry}
ArgumentError: Truncated URI
Function Use for Space becomes Leaves alone
encodeComponent a path segment or any single value %20 A-Z a-z 0-9 - _ . ! ~ * ' ( )
encodeQueryComponent a query key or value + A-Z a-z 0-9 - _ . ~
encodeFull a complete URL that has only a few bad characters %20 all reserved characters such as / ? & = #

Non-ASCII characters are encoded as UTF-8 bytes (ł becomes %C5%82). The decoders accept an encoding: argument for legacy charsets. See Unicode and encodings.

decodeComponent leaves + as is, and decodeQueryComponent turns it into a space. Use the decoder that matches where the text came from. In most code you don't need these functions at all: pathSegments, queryParameters and the Uri constructors do the encoding for you.

Equality and normalization

Uri implements == and hashCode on its normalized form, so equivalent spellings compare equal and work as map keys:

Uri canonical(Uri uri) {
  final params = uri.queryParametersAll;
  final keys = params.keys.toList()..sort();
  return uri.replace(
    queryParameters: params.isEmpty ? null : {for (final k in keys) k: params[k]!},
  );
}

void main() {
  final a = Uri.parse('HTTPS://Example.com:443/a%2fb');
  final b = Uri.parse('https://example.com/a%2Fb');
  print('$a | $b | ${a == b}');

  final c = Uri.parse('https://example.com/caf%C3%A9');
  final d = Uri.parse('https://example.com/café');
  print('$d | ${c == d}');

  print(Uri.parse('https://example.com/%7Euser'));

  final x = Uri.parse('https://example.com/?a=1&b=2');
  final y = Uri.parse('https://example.com/?b=2&a=1');
  print('${x == y}  ${canonical(x) == canonical(y)}');

  final seen = {Uri.parse('https://Dart.dev/'), Uri.parse('https://dart.dev:443/')};
  print(seen.length);
}

Output:

https://example.com/a%2Fb | https://example.com/a%2Fb | true
https://example.com/caf%C3%A9 | true
https://example.com/~user
false  true
1

Parsing lowercases the scheme and host, drops the default port, uppercases percent-escapes, encodes non-ASCII characters and decodes escapes of unreserved characters (%7E becomes ~). Query parameter order still counts, so to deduplicate URLs (for example in a crawler) sort the parameters first, as canonical does.

File URIs

Uri.file turns a file system path into a file: URI and toFilePath turns it back. Both take a windows: flag, which defaults to the current platform:

void main() {
  final unix = Uri.file('/home/me/My Docs/notes.txt', windows: false);
  print(unix);
  print(unix.toFilePath(windows: false));

  final win = Uri.file(r'C:\Users\me\My Docs\notes.txt', windows: true);
  print(win);
  print(win.toFilePath(windows: true));
  print(win.pathSegments);

  final unc = Uri.file(r'\\server\share\report.pdf', windows: true);
  print('$unc host=${unc.host}');

  final dir = Uri.directory('/var/www/', windows: false);
  print(dir.resolve('img/logo.png').toFilePath(windows: false));

  final rel = Uri.file('lib/main.dart', windows: false);
  print('$rel isAbsolute=${rel.isAbsolute}');
}

Output:

file:///home/me/My%20Docs/notes.txt
/home/me/My Docs/notes.txt
file:///C:/Users/me/My%20Docs/notes.txt
C:\Users\me\My Docs\notes.txt
[C:, Users, me, My Docs, notes.txt]
file://server/share/report.pdf host=server
/var/www/img/logo.png
lib/main.dart isAbsolute=false

Uri.directory makes sure the path ends with /, so resolve adds to the directory instead of replacing its last component. You get file: URIs from Platform.script, Isolate.resolvePackageUri and package configuration files. Convert them with toFilePath() before you pass them to File.

Data URIs

data: URIs carry their content inline. Uri.dataFromString builds one, and the data getter returns a UriData that decodes it. The getter is null for any other scheme:

void main() {
  final uri = Uri.dataFromString('Hello, Dart!', mimeType: 'text/plain');
  print(uri);
  final parsed = Uri.parse('data:text/plain;base64,SGVsbG8sIERhcnQh');
  final data = parsed.data!;
  print('${data.mimeType} base64=${data.isBase64} "${data.contentAsString()}"');
  print(Uri.parse('https://example.com').data);
}

Output:

data:,Hello,%20Dart!
text/plain base64=true "Hello, Dart!"
null

text/plain is the default MIME type, so it's left out of the output. For binary payloads, see Base64 and hex encoding.

Routing on path segments

pathSegments is a List<String>, so Dart 3 pattern matching makes a small router. In a dart:io server, request.uri is a Uri like this one, holding the path and query:

String route(Uri uri) {
  final limit = int.tryParse(uri.queryParameters['limit'] ?? '') ?? 20;
  return switch (uri.pathSegments) {
    [] => 'home',
    ['users'] => 'list users (limit $limit)',
    ['users', final id] when int.tryParse(id) != null => 'show user $id',
    ['users', final id, 'posts', ...final rest] =>
      'posts of user $id, extra: $rest',
    ['files', ...final path] => 'file "${path.join('/')}"',
    _ => '404 ${uri.path}',
  };
}

void main() {
  for (final s in [
    '/',
    '/users?limit=5',
    '/users/42',
    '/users/abc',
    '/users/7/posts/2024/06',
    '/files/My%20Docs/a.txt',
    '/nope',
  ]) {
    print('${s.padRight(26)} => ${route(Uri.parse(s))}');
  }
}

Output:

/                          => home
/users?limit=5             => list users (limit 5)
/users/42                  => show user 42
/users/abc                 => 404 /users/abc
/users/7/posts/2024/06     => posts of user 7, extra: [2024, 06]
/files/My%20Docs/a.txt     => file "My Docs/a.txt"
/nope                      => 404 /nope

The segments are already decoded (My%20Docs becomes My Docs). If you join them back into a file path, reject .. segments first, or a request can escape the directory you meant to serve.

Quick reference

Task Code
Parse, throw on error Uri.parse(s)
Parse, null on error Uri.tryParse(s)
One query value uri.queryParameters['k']
All values of a repeated key uri.queryParametersAll['k']
Decoded path parts uri.pathSegments
Build an https URL Uri.https('host:port', '/path', {'k': 'v'})
Change one parameter uri.replace(queryParameters: {...uri.queryParameters, 'k': 'v'})
Append path segments uri.replace(pathSegments: [...uri.pathSegments, 'x'])
Relative to absolute base.resolve('../x.html')
Encode a query value Uri.encodeQueryComponent(v)
Encode a path segment Uri.encodeComponent(v)
Path to file: URI and back Uri.file(path), uri.toFilePath()

Uri objects go straight into the http package (http.get(uri)) and into HttpClient. See HTTP Request, REST APIs and OAuth.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents