On this page11 sections
Lecture 057: URIs
| Day | Extra Topics |
| Lecture | 057 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Every web address is a URI (Uniform Resource Identifier). Apps build them all the time: to call an API, open a link or share a page. Dart's
Uriclass takes addresses apart and builds them safely, so spaces and symbols never break your links.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 009 (strings), 010 (null safety) and 014 (maps).
Learning Objectives
- Name the parts of a URI
- Read the parts with
Uri.parse - Build a URI with
Uri(...)andUri.https(...) - Encode and decode text for URLs
- Change or resolve a URI
1. The Parts of a URI
https://codingmentor.app:443/courses/dart?lesson=9&lang=en#examples
└─┬─┘ └──────┬───────┘ └┬┘└─────┬────┘ └───────┬───────┘ └──┬───┘
scheme host port path query fragmentUri.parse splits a string into these parts:
var uri = Uri.parse('https://codingmentor.app:443/courses/dart?lesson=9&lang=en#examples');
print(uri.scheme); // https
print(uri.host); // codingmentor.app
print(uri.port); // 443
print(uri.path); // /courses/dart
print(uri.pathSegments); // [courses, dart]
print(uri.query); // lesson=9&lang=en
print(uri.queryParameters); // {lesson: 9, lang: en}
print(uri.queryParameters['lesson']); // 9
print(uri.fragment); // examplesqueryParameters is a Map<String, String>, so the values are always strings.
2. Building a URI
Don't glue URLs together by hand. Give Uri the parts and let it handle spaces and symbols:
var built = Uri(
scheme: 'https',
host: 'api.example.com',
path: '/search',
queryParameters: {'q': 'dart & flutter', 'page': '2'},
);
print(built);
// https://api.example.com/search?q=dart+%26+flutter&page=2Uri.https is a shortcut for the common case:
var https = Uri.https('api.example.com', '/users/7', {'fields': 'name,email'});
print(https);
// https://api.example.com/users/7?fields=name%2CemailThe http package (used in the APIs course) takes exactly this kind of Uri.
3. Encoding and Decoding
Some characters (spaces, &, ?, #) have special meanings in a URL, so they're written as
% codes:
print(Uri.encodeComponent('dart & flutter?')); // dart%20%26%20flutter%3F
print(Uri.decodeComponent('dart%20%26%20flutter%3F')); // dart & flutter?
print(Uri.encodeFull('https://example.com/a b?x=1 2')); // https://example.com/a%20b?x=1%202encodeComponentis for one piece (a search word, a name).encodeFullis for a whole URL; it leaves/,?,&alone.
When you build with Uri(...) or Uri.https(...), encoding is done for you.
4. Changing and Resolving
var updated = uri.replace(queryParameters: {'lesson': '10'});
print(updated);
// https://codingmentor.app/courses/dart?lesson=10#examples
var base = Uri.parse('https://codingmentor.app/courses/dart/');
print(base.resolve('lectures/010')); // https://codingmentor.app/courses/dart/lectures/010
print(base.resolve('../flutter')); // https://codingmentor.app/courses/flutterreplace makes a copy with some parts changed. A Uri never changes itself, just like a
String. resolve works out where a relative link points, the way a browser does. (The
:443 disappears because it's the normal port for https.)
Code Examples
Example 1: A Weather API Address
Uri weatherUrl(String city, {bool metric = true, int days = 3}) {
return Uri.https('api.weather.example', '/v1/forecast', {
'city': city,
'units': metric ? 'metric' : 'imperial',
'days': '$days',
});
}
void main() {
var url = weatherUrl('Dera Ismail Khan', days: 5);
print(url);
var back = Uri.parse(url.toString());
print('City: ${back.queryParameters['city']}');
print('Days: ${int.parse(back.queryParameters['days']!)}');
print('Secure: ${back.scheme == 'https'}');
}Output
https://api.weather.example/v1/forecast?city=Dera+Ismail+Khan&units=metric&days=5
City: Dera Ismail Khan
Days: 5
Secure: trueThe spaces in the city name are encoded automatically, and decoded again when the URL is parsed.
Query values must be strings, so days is written as '$days'.
Common Beginner Mistakes
1. Building a URL by joining strings
var q = 'dart & flutter';
var url = 'https://api.example.com/search?q=$q&page=2';
print(Uri.parse(url).queryParameters);Output
{q: dart , flutter: , page: 2}No error, but the & inside the search text split it into a broken extra parameter. Use
Uri.https(...) with a queryParameters map.
2. Treating a query value as a number
var uri = Uri.parse('https://example.com/?page=2');
int page = uri.queryParameters['page'];Error: A value of type 'String?' can't be assigned to a variable of type 'int'.Values are String?: they're text, and the key might be missing. Use
int.tryParse(uri.queryParameters['page'] ?? '') ?? 1.
3. Passing numbers in queryParameters: the map must contain strings: write 'page': '2'
or 'page': '$page', not 'page': 2.
Practice Questions
- In
https://shop.pk/cart?item=7#top, what are the host, path, query and fragment? - What type is
uri.queryParameters['id']? - Which is safer:
'https://x.com/search?q=$text'orUri.https('x.com', '/search', {'q': text})? Why? - What does
Uri.encodeComponent('a b')give? - With
base = Uri.parse('https://site.com/docs/'), what isbase.resolve('intro')?
Practice Answers
- Host
shop.pk, path/cart, queryitem=7, fragmenttop. String?Uri.https(...): it encodes special characters like spaces and&, so the URL can't break.a%20bhttps://site.com/docs/intro
Key Takeaways
- A URI has a scheme, host, port, path, query and fragment.
Uri.parsereads the parts;queryParametersis a map of strings.- Build with
Uri(...)orUri.https(...); never join URL strings by hand. encodeComponent/decodeComponenthandle special characters.replacecopies with changes;resolvefollows relative links.