Sub topic 3
Reading a URI: scheme, host, path, and query
This chapter covers how Dart splits an incoming link into the parts a router needs. It assumes you know Dart and basic Flutter widgets, and that you can name the parts of a URL. Later chapters use these parts in go_router. Here we focus on how Uri behaves, including the edge cases that cause bugs.
Why parsing comes first
A deep link arrives in your app as a string. Before the app can open a screen, it has to answer three questions:
- Is this link meant for this app? The scheme and host answer that.
- Which screen should open? The path answers that.
- What data does the screen need? The path parameters and the query answer that.
Dart's Uri class answers all three. go_router calls it for you, but you will still read Uri values in redirects, error screens, and manual link handlers.
The parts of a URI
Take this link:
https://example.com:8080/products/42?ref=email&tag=a&tag=b#reviews| Part | Value | Dart property |
|---|---|---|
| Scheme | `https` | `uri.scheme` |
| Host | `example.com` | `uri.host` |
| Port | `8080` | `uri.port` |
| Path | `/products/42` | `uri.path` |
| Path segments | `products`, `42` | `uri.pathSegments` |
| Query | `ref=email&tag=a&tag=b` | `uri.query` |
| Fragment | `reviews` | `uri.fragment` |
The scheme says how to interpret the rest. For https links, the host names the domain that owns the link. That ownership is what Android App Links and iOS Universal Links verify, as later chapters show. The path chooses a screen, and the query carries optional values.
Parsing with Dart's Uri class
Uri.parse turns a string into a Uri object. The properties then give you each part.
void main() {
final uri = Uri.parse('https://example.com/products/42?ref=email');
print(uri.scheme); // https
print(uri.host); // example.com
print(uri.pathSegments); // [products, 42]
print(uri.queryParameters['ref']); // email
}Use pathSegments instead of splitting path on / yourself. It handles the leading slash and decodes percent-escapes for you.
Path versus path segments
path is a single string. pathSegments is a list.
void main() {
final uri = Uri.parse('https://example.com/products/42/');
print(uri.path); // /products/42/
print(uri.pathSegments); // [products, 42, ]
print(uri.pathSegments.length); // 3
}A trailing slash produces an empty last segment. Code that checks pathSegments.length == 2 would reject this link even though most users would consider it the same page. If you match paths by hand, decide whether to accept a trailing slash. go_router handles this case for you, as the router chapter shows.
Query parameters
queryParameters is a Map<String, String>. It is convenient, but it keeps only one value per key.
void main() {
final uri = Uri.parse('https://example.com/search?tag=a&tag=b&q=shoes');
print(uri.queryParameters); // {tag: b, q: shoes}
print(uri.queryParametersAll); // {tag: [a, b], q: [shoes]}
}When a key repeats, queryParameters keeps the last value. Use queryParametersAll when a key can repeat, such as a filter with several tags. It returns Map<String, List<String>>.
A missing key returns null, not an empty string. Always handle the null case:
void main() {
final uri = Uri.parse('https://example.com/products/42');
final ref = uri.queryParameters['ref'] ?? 'none';
print(ref); // none
}A key with no value, as in ?debug, appears in the map with an empty string as its value. That is different from the key being absent.
Percent-encoding
URLs can only contain a limited set of characters. Other characters, such as spaces or & inside a value, are written as % followed by two hex digits. A space becomes %20, and & becomes %26.
void main() {
final uri = Uri.parse('https://example.com/search?q=red%20shoes%26socks');
print(uri.query); // q=red%20shoes%26socks
print(uri.queryParameters['q']); // red shoes&socks
}query returns the raw, still-encoded text. queryParameters and pathSegments return decoded values. This difference matters when you build links. If you insert user text into a URL by string concatenation, a value containing & or # silently changes the link's meaning. Build links with the Uri constructor, which encodes for you:
void main() {
final uri = Uri(
scheme: 'https',
host: 'example.com',
pathSegments: ['search'],
queryParameters: {'q': 'red shoes&socks'},
);
print(uri); // https://example.com/search?q=red+shoes%26socks
}Note that the constructor writes the space as +. That is valid in a query string, and queryParameters decodes it back to a space.
When you need to encode a whole URL as a single value, for example the from parameter in a login redirect, use Uri.encodeComponent. It escapes /, ?, &, and #, so the inner URL cannot break the outer one.
Custom schemes versus https links
The same parser handles both kinds of link, but the parts mean different things.
void main() {
final custom = Uri.parse('myapp://products/42');
print(custom.scheme); // myapp
print(custom.host); // products
print(custom.pathSegments); // [42]
final web = Uri.parse('https://example.com/products/42');
print(web.host); // example.com
print(web.pathSegments); // [products, 42]
}In myapp://products/42, the word products lands in the host position because the parser follows the URL grammar, not your intent. If you use a custom scheme, decide up front whether the first word is a host or part of the path, and write one convention into your router. With https links the host is a real domain, which keeps the layout predictable.
Diagram: where each part is used
Edge cases to handle
Uri.parse throws a FormatException on input it cannot parse, such as a link with an invalid port. Links come from outside your app, so treat them as untrusted. Use Uri.tryParse when the input might be malformed. It returns null instead of throwing.
void main() {
final bad = Uri.tryParse('https://example.com:abc/products');
print(bad); // null
final ok = Uri.tryParse('https://example.com/products/42');
print(ok?.pathSegments); // [products, 42]
}Other cases that often surprise people:
- Case.
Urilowercases the scheme and host but leaves the path alone.HTTPS://Example.COM/Productsgives schemehttps, hostexample.com, and path/Products. Paths are case-sensitive in most routers. - Missing host. A link such as
myapp:///products/42has an empty host. A check likeuri.host == 'example.com'rejects it. - Fragment. The part after
#is not part of the path or query. Do not expect it inqueryParameters. - Everything is a string. The
42in/products/42is the text"42". Parse it withint.tryParseand handlenull.
void main() {
final uri = Uri.parse('https://example.com/products/42');
final id = int.tryParse(uri.pathSegments.last);
if (id == null) {
print('Not a valid product id');
} else {
print('Open product $id');
}
}Reading a URI inside go_router
You will rarely call Uri.parse on a deep link yourself, because go_router passes the parsed Uri to your builders as state.uri. The properties you learned here apply directly:
final id = state.pathParameters['id']!;
final ref = state.uri.queryParameters['ref'];state.pathParameters holds values captured from the route pattern, such as :id. state.uri.queryParameters is the same map you saw above, with the same single-value behavior for repeated keys.
Exercise
A link arrives as https://example.com/search?tag=red&tag=blue&q=a%26b. What do uri.queryParameters['tag'] and uri.queryParameters['q'] return, and which property would you use to get both tags?
Show answer
queryParameters['tag'] returns blue, because a repeated key keeps only its last value. queryParameters['q'] returns a&b, because the %26 is decoded. Use uri.queryParametersAll['tag'], which returns [red, blue].
Exercise
You write Uri.parse('myapp://orders/7'). What are uri.host and uri.pathSegments, and why might this surprise you if you expected "orders" to be part of the path?
Show answer
uri.host is orders and uri.pathSegments is [7]. The parser treats the text after the double slash as the host, following URL grammar. Choose one convention for custom schemes, either reading the host as the first section or writing links as myapp:///orders/7 so everything is in the path.