On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Parts of a URI
  4. 2. Building a URI
  5. 3. Encoding and Decoding
  6. 4. Changing and Resolving
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 057: URIs

DayExtra Topics
Lecture057 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

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 Uri class 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(...) and Uri.https(...)
  • Encode and decode text for URLs
  • Change or resolve a URI

1. The Parts of a URI

code
https://codingmentor.app:443/courses/dart?lesson=9&lang=en#examples
└─┬─┘   └──────┬───────┘ └┬┘└─────┬────┘ └───────┬───────┘ └──┬───┘
scheme       host       port    path          query         fragment

Uri.parse splits a string into these parts:

dart
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);                   // examples

queryParameters 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:

dart
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=2

Uri.https is a shortcut for the common case:

dart
var https = Uri.https('api.example.com', '/users/7', {'fields': 'name,email'});
print(https);
// https://api.example.com/users/7?fields=name%2Cemail

The 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:

dart
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%202
  • encodeComponent is for one piece (a search word, a name).
  • encodeFull is for a whole URL; it leaves /, ?, & alone.

When you build with Uri(...) or Uri.https(...), encoding is done for you.

4. Changing and Resolving

dart
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/flutter

replace 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

dart
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

code
https://api.weather.example/v1/forecast?city=Dera+Ismail+Khan&units=metric&days=5
City: Dera Ismail Khan
Days: 5
Secure: true

The 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

dart
var q = 'dart & flutter';
var url = 'https://api.example.com/search?q=$q&page=2';
print(Uri.parse(url).queryParameters);

Output

code
{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

dart
var uri = Uri.parse('https://example.com/?page=2');
int page = uri.queryParameters['page'];
code
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

  1. In https://shop.pk/cart?item=7#top, what are the host, path, query and fragment?
  2. What type is uri.queryParameters['id']?
  3. Which is safer: 'https://x.com/search?q=$text' or Uri.https('x.com', '/search', {'q': text})? Why?
  4. What does Uri.encodeComponent('a b') give?
  5. With base = Uri.parse('https://site.com/docs/'), what is base.resolve('intro')?

Practice Answers

  1. Host shop.pk, path /cart, query item=7, fragment top.
  2. String?
  3. Uri.https(...): it encodes special characters like spaces and &, so the URL can't break.
  4. a%20b
  5. https://site.com/docs/intro

Key Takeaways

  • A URI has a scheme, host, port, path, query and fragment.
  • Uri.parse reads the parts; queryParameters is a map of strings.
  • Build with Uri(...) or Uri.https(...); never join URL strings by hand.
  • encodeComponent / decodeComponent handle special characters.
  • replace copies with changes; resolve follows relative links.