Menu
Coddy logo textTech

Libraries & Imports

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 2 of 110.

Dart comes with a rich set of built-in libraries you can import using the import 'dart:libraryname'; syntax.

Some commonly used built-in libraries:

  • dart:math — mathematical functions and constants
  • dart:io — file, socket, and standard I/O support
  • dart:core — automatically imported, provides basic types

Import the dart:math library to use math functions

import 'dart:math';

Use functions and constants from the library

void main() {
  print(sqrt(25));           // 5.0
  print(pi.toStringAsFixed(5)); // 3.14159
  print(pow(2, 10));         // 1024
}

Output:

5.0
3.14159
1024

You can also import a file of your own alongside a built-in library. Both types of imports work the same way — the difference is whether the path starts with dart: (built-in) or a filename string (local file).

import 'dart:math';         // built-in library
import 'my_helpers.dart';  // your own file
challenge icon

Challenge

Medium

You are given math_tools.dart which already uses dart:math internally. Add the correct import statement in driver.dart to bring in math_tools.dart so you can call its functions!

  • math_tools.dart: Contains getSquareRoot(n) and getPI() functions (locked)
  • driver.dart: Add the import and the rest will work

Cheat sheet

Import built-in libraries using import 'dart:libraryname'; syntax:

import 'dart:math';

Commonly used built-in libraries:

  • dart:math — mathematical functions and constants
  • dart:io — file, socket, and standard I/O support
  • dart:core — automatically imported, provides basic types

Example using dart:math:

import 'dart:math';

void main() {
  print(sqrt(25));           // 5.0
  print(pi.toStringAsFixed(5)); // 3.14159
  print(pow(2, 10));         // 1024
}

Import your own files using a filename string:

import 'dart:math';         // built-in library
import 'my_helpers.dart';  // your own file

Try it yourself

// TODO: Import math_tools.dart to use getSquareRoot and getPI

import 'dart:io';

void main() {
  String testCase = stdin.readLineSync()!;

  if (testCase == 'sqrt_test') {
    print(getSquareRoot(25).toInt());
  } else if (testCase == 'pi_test') {
    print(getPI().toStringAsFixed(5));
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming