Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 61 ยท Errors and Libraries

Core Libraries: dart:core, math, convert, collection

A tour of Dart's built-in libraries: DateTime and Duration, RegExp, jsonEncode and jsonDecode, Uri, Random, dart:math and dart:collection, with runnable stand-ins.

The Dart SDK ships with a rich standard library, and you can use it without installing any package. dart:core is imported automatically. The others, dart:math, dart:convert, dart:collection and dart:async, need an import line (see Libraries, Imports and Packages). In this lesson you meet the pieces you will use almost every day: dates and durations, regular expressions, JSON, URIs, random numbers and a few extra collections.

The Dart code is read-only. The TypeScript stand-ins use JavaScript's Date, RegExp, JSON and URL, which are close relatives, so you can run the same ideas.

DateTime and Duration

A DateTime is a point in time; a Duration is a length of time. Both are immutable, so every operation returns a new object.

DART
void main() {
  var launch = DateTime(2025, 3, 14, 9, 30);          // local time
  var utc = DateTime.utc(2025, 3, 14, 9, 30);         // UTC
  var parsed = DateTime.parse('2025-03-14T09:30:00Z'); // from ISO 8601 text
  var now = DateTime.now();

  var later = utc.add(const Duration(days: 2, hours: 3));
  print(later.toIso8601String());      // 2025-03-16T12:30:00.000Z
  print(later.weekday);                // 7 (Sunday): Monday is 1
  print(later.isAfter(utc));           // true

  Duration gap = later.difference(utc);
  print(gap.inHours);                  // 51
  print(gap.inDays);                   // 2 (whole days only)
  print(gap);                          // 51:00:00.000000
}

Useful members: year, month, day, hour, weekday, isBefore, isAfter, compareTo, millisecondsSinceEpoch and toUtc(). Values outside the normal range roll over: DateTime(2025, 1, 32) is February 1. That is handy for "the day after" arithmetic.

Two traps are worth knowing. First, Duration has no months or years, because they have no fixed length. Second, adding Duration(days: 1) to a local time is exactly 24 hours, which is not "the same clock time tomorrow" across a daylight-saving change. If you need exact calendar logic, do the arithmetic in UTC or build a new DateTime from the parts.

Comparing, taking apart and timing

DateTime objects compare with isBefore, isAfter, isAtSameMomentAs and compareTo (the last one is what sort needs). The parts are plain getters: year, month (1 to 12), day, hour, minute, second, millisecond and weekday (Monday is 1). millisecondsSinceEpoch counts from the Unix epoch, midnight on 1 January 1970 UTC, and DateTime.fromMillisecondsSinceEpoch(ms) goes back. For a date without a time, drop the time part by building DateTime(d.year, d.month, d.day).

DART
void main() {
  var a = DateTime.utc(2025, 3, 14);
  var b = DateTime.utc(2025, 12, 25);
  print(a.isBefore(b));                         // true
  print(b.difference(a).inDays);                // 286
  print(a.millisecondsSinceEpoch);              // 1741910400000
  print(DateTime.fromMillisecondsSinceEpoch(0, isUtc: true)); // 1970-01-01 00:00:00.000Z

  // Measuring how long some work takes:
  var watch = Stopwatch()..start();
  var sum = 0;
  for (var i = 0; i < 1000000; i++) { sum += i; }
  watch.stop();
  print('took ${watch.elapsedMilliseconds} ms');
}

Stopwatch measures elapsed time with a monotonic clock, so it is the right tool for timing code. DateTime.now() can jump when the system clock changes. DateTime has no formatting method beyond toString and toIso8601String; for custom patterns, use the intl package's DateFormat.

TypeScript Dates and durations (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

RegExp

RegExp compiles a pattern. Write patterns as raw strings (r'...') so backslashes are not treated as escapes:

DART
void main() {
  var date = RegExp(r'(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})');
  var text = 'Released 2025-03-14, patched 2025-04-02.';

  print(date.hasMatch(text));                 // true

  RegExpMatch? first = date.firstMatch(text);
  print(first?.group(0));                     // 2025-03-14
  print(first?.namedGroup('month'));          // 03

  for (var m in date.allMatches(text)) {
    print('${m.namedGroup('day')}/${m.namedGroup('month')}');   // 14/03, then 02/04
  }

  var hidden = text.replaceAllMapped(date, (m) => '${m[1]}-**-**');
  print(hidden);   // Released 2025-**-**, patched 2025-**-**.
}

group(0) is the whole match, group(1) the first parenthesized group, and namedGroup('x') reads (?<x>...). The pattern options are named arguments: RegExp(r'hello', caseSensitive: false, multiLine: true). String has matching helpers: contains, replaceAll, replaceFirst, split and allMatches all accept patterns. Be careful with patterns taken from user input: use RegExp.escape(text) to match a literal string.

Uri

Uri parses, builds and encodes web addresses. It understands the parts, so you do not need to cut strings by hand:

DART
void main() {
  var uri = Uri.parse('https://example.com:8080/search?q=dart&page=2#results');
  print(uri.scheme);                 // https
  print(uri.host);                   // example.com
  print(uri.port);                   // 8080
  print(uri.path);                   // /search
  print(uri.queryParameters);        // {q: dart, page: 2}
  print(uri.fragment);               // results

  var built = Uri.https('example.com', '/search', {'q': 'dart', 'page': '2'});
  print(built);                      // https://example.com/search?q=dart&page=2

  var next = uri.replace(queryParameters: {'q': 'dart', 'page': '3'});
  print(next.query);                 // q=dart&page=3

  print(Uri.encodeComponent('a b&c')); // a%20b%26c
}

Which encoder to use matters. Uri.encodeComponent escapes every character that has special meaning in a URL (&, =, /, ?, #, spaces), so it is for one piece, such as a query value. Uri.encodeFull escapes only what can never appear in an address (spaces and non-ASCII characters) and leaves the structure characters alone, so it is for a whole address. Uri.decodeComponent and Uri.decodeFull reverse them:

DART
void main() {
  print(Uri.encodeFull('https://example.com/my file?q=a b&x=1'));
  // https://example.com/my%20file?q=a%20b&x=1
  print(Uri.encodeComponent('https://example.com/my file?q=a b&x=1'));
  // https%3A%2F%2Fexample.com%2Fmy%20file%3Fq%3Da%20b%26x%3D1
  print(Uri.decodeComponent('a%20b%26c'));      // a b&c
}

Let Uri.https(...) and queryParameters do the encoding. Joining strings with '?q=$text' breaks as soon as the text contains &, # or a space. uri.resolve('../other') turns a relative reference into a full address.

TypeScript Regular expressions and URLs (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

JSON with dart:convert

dart:convert turns data into text and back. The two functions you use most are jsonEncode and jsonDecode:

DART
import 'dart:convert';

void main() {
  var data = {
    'name': 'Ada',
    'tags': ['math', 'code'],
    'active': true,
    'score': 9.5,
    'manager': null,
  };

  String text = jsonEncode(data);
  print(text);   // {"name":"Ada","tags":["math","code"],"active":true,"score":9.5,"manager":null}

  Object? back = jsonDecode(text);          // a Map<String, dynamic> underneath
  if (back is Map<String, dynamic>) {
    print(back['name']);                    // Ada
    print((back['tags'] as List).length);   // 2
  }

  var pretty = const JsonEncoder.withIndent('  ').convert(data);
  print(pretty);
}

jsonDecode returns dynamic, so check the shape before trusting it, as in the example above. Only maps with string keys, lists, strings, numbers, booleans and null can be encoded directly. For your own classes, give them a toJson() method and jsonEncode will call it, or pass a toEncodable function. A full lesson on mapping classes to JSON follows in JSON and Serialization.

The same library has utf8.encode and utf8.decode (text to bytes and back), base64Encode, base64Decode and LineSplitter for reading text line by line.

Random and dart:math

Random lives in dart:math, together with min, max, sqrt, pow, sin, cos, pi and e:

DART
import 'dart:math';

void main() {
  var rng = Random();                       // different each run
  var seeded = Random(42);                  // same sequence each run for a given SDK

  print(rng.nextInt(10));                   // 0 to 9: the limit is exclusive
  print(rng.nextDouble());                  // 0.0 up to, not including, 1.0
  print(rng.nextBool());

  print(max(3, 7));                         // 7
  print(pow(2, 10));                        // 1024
  print(sqrt(81));                          // 9.0

  var secure = Random.secure();             // cryptographically strong, for tokens
  print(secure.nextInt(256));
}

A seed makes the sequence repeatable inside one SDK version, which helps tests and simulations. Do not rely on the exact numbers across versions. For passwords, tokens and keys always use Random.secure().

TypeScript JSON round trip and a seeded random generator (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

dart:collection

dart:core already has List, Set and Map. The dart:collection library adds specialised collections:

DART
import 'dart:collection';

void main() {
  var queue = Queue<String>()..addAll(['a', 'b']);
  queue.addFirst('start');
  queue.addLast('end');
  print(queue.removeFirst());          // start
  print(queue);                        // {a, b, end}

  var sorted = SplayTreeMap<String, int>()..addAll({'pear': 2, 'apple': 5});
  print(sorted.keys.toList());         // [apple, pear]

  var view = UnmodifiableListView([1, 2, 3]);
  // view.add(4);  // would throw UnsupportedError
  print(view.length);                  // 3
}

Queue is a double-ended queue with fast adds and removes at both ends (a List is slow at the front). SplayTreeMap and SplayTreeSet keep their elements sorted. HashMap and HashSet trade ordering for speed, while LinkedHashMap (the default) remembers insertion order. The package:collection package adds even more helpers, such as groupBy and DelegatingList.

flowchart LR
    C["dart:core<br/>always available"] --> T["DateTime, Duration, RegExp,<br/>Uri, List, Map, Set, String"]
    M["dart:math"] --> R["Random, max, min,<br/>sqrt, pow, pi"]
    V["dart:convert"] --> J["jsonEncode, jsonDecode,<br/>utf8, base64"]
    Q["dart:collection"] --> X["Queue, SplayTreeMap,<br/>UnmodifiableListView"]

The libraries in this lesson: only dart:core is imported for you; the others need an import.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Random().nextInt(6) return?

    The argument is an exclusive upper limit, so the result is 0, 1, 2, 3, 4 or 5. Add 1 for a dice roll.
  2. 2. What type does jsonDecode give you for a JSON object?

    jsonDecode returns dynamic. An object becomes a Map<String, dynamic>, an array a List, so check the shape with is before using it.
  3. 3. Why should you build query strings with Uri.https(host, path, queryParameters)?

    Uri encodes each value, so characters like &, # and spaces cannot break the address. Concatenated strings do not.
  4. 4. Why are regular expression patterns usually written as raw strings (r'...') in Dart?

    In a raw string a backslash is just a backslash, so the pattern is written once and reads like the regex itself.
  5. 5. Which duration unit does Duration NOT have a constructor argument for?

    Months and years have no fixed length, so Duration only counts fixed units: days, hours, minutes, seconds, milliseconds and microseconds.

Summary

  • DateTime and Duration are immutable; use UTC for exact arithmetic and remember weekday runs from 1 (Monday) to 7 (Sunday).
  • RegExp supports groups and named groups; write patterns as raw strings.
  • Uri parses and builds addresses and encodes values safely.
  • jsonEncode and jsonDecode live in dart:convert; the decoded value is dynamic, so check its shape.
  • Random(seed) is repeatable, Random.secure() is for secrets, and nextInt(n) excludes n.
  • dart:collection adds Queue, SplayTreeMap and friends.

Next, move from memory to the disk with Files, Directories and Command-Line Programs.