Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 17 of 19 · 5 min read

Dart core libraries: JSON, dates and more

Dart core library notes with examples: dart:math and Random, JSON with jsonEncode, jsonDecode and fromJson, DateTime, Duration, RegExp, Uri and stdin.

The core libraries

Dart ships with libraries you import by name. dart:core (numbers, strings, lists, DateTime, RegExp, Uri) is imported automatically. Others need an import at the top of the file:

LibraryFor
dart:mathsqrt, pow, min, max, pi, Random
dart:convertJSON, UTF-8 and Base64
dart:asyncTimer, StreamController, Completer
dart:iofiles, stdin, HTTP servers (command line and mobile, not the web)
dart:collectionQueue, SplayTreeMap and other collections

dart:math and Random

import 'dart:math';

void main() {
  print(sqrt(2).toStringAsFixed(3));
  print(pow(1.05, 10).toStringAsFixed(3));   // 5% growth for 10 years
  print(min(4, 9));
  print((sin(pi / 2)).round());

  var rng = Random(7);                       // a seed gives the same numbers every run
  var dice = rng.nextInt(6) + 1;             // 1 to 6
  print(dice >= 1 && dice <= 6);
}
1.414
1.629
4
1
true

Random() without a seed gives different numbers on every run; Random.secure() is for passwords and tokens.

JSON: jsonEncode and jsonDecode

JSON is the text format apps and servers use to exchange data. dart:convert turns Dart maps and lists into JSON text and back.

import 'dart:convert';

void main() {
  var student = {'name': 'Asha', 'marks': [88, 92], 'passed': true};
  String text = jsonEncode(student);
  print(text);

  var back = jsonDecode('{"name":"Rohit","marks":[74,81],"passed":true}');
  print(back['name']);
  print((back['marks'] as List).length);
}
{"name":"Asha","marks":[88,92],"passed":true}
Rohit
2

jsonDecode returns dynamic: maps become Map<String, dynamic> and arrays List<dynamic>. JsonEncoder.withIndent(' ').convert(data) prints it neatly.

From JSON to objects: fromJson and toJson

Working with raw maps is error-prone: a typo in a key compiles and gives null. The standard pattern is a class with a fromJson constructor and a toJson method:

import 'dart:convert';

class Student {
  final String name;
  final int marks;
  Student(this.name, this.marks);

  factory Student.fromJson(Map<String, dynamic> j) =>
      Student(j['name'] as String, j['marks'] as int);

  Map<String, dynamic> toJson() => {'name': name, 'marks': marks};
}

void main() {
  const body = '[{"name":"Asha","marks":88},{"name":"Rohit","marks":74}]';
  var list = (jsonDecode(body) as List)
      .map((e) => Student.fromJson(e as Map<String, dynamic>))
      .toList();
  for (var s in list) {
    print('${s.name}: ${s.marks}');
  }
  print(jsonEncode(list));   // calls toJson on each object
}
Asha: 88
Rohit: 74
[{"name":"Asha","marks":88},{"name":"Rohit","marks":74}]

factory constructors may return an object built another way, which suits parsing. Flutter apps use exactly this pattern for API responses; larger projects generate it with json_serializable.

DateTime and Duration

void main() {
  var exam = DateTime(2026, 3, 15, 10, 30);     // 15 March 2026, 10:30
  print(exam);
  print(exam.weekday);                          // 1 = Monday ... 7 = Sunday
  var result = exam.add(Duration(days: 21));
  print('${result.day}/${result.month}/${result.year}');

  var start = DateTime(2026, 1, 1);
  print(exam.difference(start).inDays);
  print(exam.isAfter(start));

  var d = Duration(hours: 1, minutes: 45);
  print(d.inMinutes);
  print(DateTime.parse('2026-08-15').month);
}
2026-03-15 10:30:00.000
7
5/4/2026
73
true
105
8

DateTime.now() gives the current date and time. toIso8601String() and DateTime.parse convert to and from the standard text form used in JSON. For formats such as "15 Mar 2026", use the intl package.

RegExp: find and validate patterns

A regular expression describes a text pattern.

void main() {
  var pin = RegExp(r'^\d{6}$');
  print(pin.hasMatch('834001'));
  print(pin.hasMatch('8340'));

  String sms = 'Rs 2500 debited, balance Rs 14320 on 05-12-2026';
  var nums = RegExp(r'\d+').allMatches(sms).map((m) => m.group(0)!).toList();
  print(nums);

  var email = RegExp(r'[a-z.]+@[a-z]+\.[a-z]+');
  print(email.firstMatch('mail asha.k@example.com now')?.group(0));
  print('a1b2c3'.replaceAll(RegExp(r'[0-9]'), ''));
}
true
false
[2500, 14320, 05, 12, 2026]
asha.k@example.com
abc

Write patterns as raw strings (r'...') so \d is not treated as an escape. ^ and $ anchor the start and end, \d is a digit, {6} means exactly six, + one or more.

Uri and Stopwatch

void main() {
  var u = Uri.parse('https://brainbit-teaching.com/courses?topic=dart&level=1');
  print(u.host);
  print(u.path);
  print(u.queryParameters['topic']);

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

  var sw = Stopwatch()..start();
  var sum = 0;
  for (var i = 0; i < 1000000; i++) {
    sum += i;
  }
  sw.stop();
  print(sum);
  print(sw.elapsedMilliseconds >= 0);
}
brainbit-teaching.com
/courses
dart
https://example.com/search?q=dart+notes
499999500000
true

Uri builds and reads web addresses safely, encoding spaces and special characters. Stopwatch measures how long code takes.

Reading input with stdin

Command-line programs read typed input with stdin.readLineSync() from dart:io. It returns String? (null at the end of input):

import 'dart:io';

void main() {
  stdout.write('Your name: ');
  String name = stdin.readLineSync() ?? '';
  stdout.write('Your age: ');
  int age = int.tryParse(stdin.readLineSync() ?? '') ?? 0;
  print('Hello $name, next year you will be ${age + 1}.');
}

Run it with dart run file.dart in a terminal. dart:io is not available in DartPad or on the web.

Common mistakes

  • Using jsonDecode results without casting, so mistakes appear only at run time.
  • Reading j['Name'] when the key is 'name': JSON keys are case-sensitive.
  • Expecting DateTime(2026, 2, 30) to fail: it quietly rolls over to 2 March.
  • Writing regex patterns in normal strings, where \d breaks.
  • Importing dart:io in code meant for Flutter web.

Key points

  • dart:math gives maths and Random; dart:convert gives jsonEncode and jsonDecode.
  • Parse JSON into classes with fromJson factories and send it back with toJson.
  • DateTime stores moments; Duration stores lengths of time; difference and add connect them.
  • RegExp validates and extracts patterns; Uri builds and reads URLs; Stopwatch times code.
  • stdin.readLineSync() reads console input in command-line programs.

Practice questions

1. Convert the map {'city': 'Ranchi', 'pin': 834001} to JSON text and back, then print the pin.
import 'dart:convert';

void main() {
  var text = jsonEncode({'city': 'Ranchi', 'pin': 834001});
  var map = jsonDecode(text);
  print(map['pin']);   // 834001
}
2. How many days are there from 1 January 2026 to 26 January 2026?
void main() {
  print(DateTime(2026, 1, 26).difference(DateTime(2026, 1, 1)).inDays);   // 25
}
3. Write a regular expression that checks a 10-digit Indian mobile number starting with 6, 7, 8 or 9.
void main() {
  var mobile = RegExp(r'^[6-9]\d{9}$');
  print(mobile.hasMatch('9876543210'));   // true
  print(mobile.hasMatch('5876543210'));   // false
}
4. Why do we write a fromJson factory instead of using the decoded map everywhere?

The class gives named, typed fields, so the compiler catches typos and wrong types. The map only fails at run time.

5. Print a random dice roll between 1 and 6.
import 'dart:math';

void main() {
  print(Random().nextInt(6) + 1);
}