How to use the dart:math library

The dart:math library contains constants, classes, and functions related to mathematical operations and random number generators.

The math library contains four classes:

  1. Random: This class contains methods to generate random bool, int, or double values.

  2. Point: This class is used for representing two-dimensional(x,y) positions.

  3. Rectangle: This class is used for representing two-dimensional rectangles. It contains four properties left, top, right, and bottom, to represent a 2D rectangle. The properties are immutable.

  4. MutableRectangle: This class is the same as the Rectangle class except that the properties of the MutableRectangle are mutable whereas the properties of the Rectangle class are immutable.

Syntax

We can use the functions of the dart:math library by importing it.

import 'dart:math';

Example

Let's create an example to use the classes and functions present in the dart:math library.

import 'dart:math';
void main() {
// math classes
var p1 = const Point(10, 20);
print('Point is ${p1}');
var rect = const Rectangle(0,0,10,10);
print('Rectangle is ${rect}');
//generate random number >= 0 and < 10.
var randomInt = Random().nextInt(10);
print('Random intValue : ${randomInt}');
//generate random boolean
var randomBool = Random().nextBool();
print('Random booleanValue : ${randomBool}');
// get square root of a nummber
var sqrtOf25 = sqrt(25);
print('Square root of 25 : ${sqrtOf25}');
// get maximum of two nnumbers
var maxVal = max(25, 22);
print(' max(25, 22) : ${maxVal}');
}

Explanation

  • Line 1: Imports the math library.

  • Line 5: Creates a new object for the Point class. We set the 10 and 20 as the value for x and y property respectively.

  • Line 9: Creates a new object for the Point class. We set 0 as the value for the left and top property and 10 as the value for the right and bottom property.

  • Line 13: Uses the nextInt method of Random class with 10 as an argument. It will return a random number greater than or equal to 0 and less than 10.

Note: <= Generated Random number < 10

  • Line 17: Uses the nextBool method of Random class. It will return a random bool value(true or false).

  • Line 21: Uses the sqrt function with 25 as an argument. This method will return the square root of 25 as a double value.

  • Line 25: Uses the max functions with 25 and 22 as an argument. This method will return the largest number between the passed arguments. In our case, we get 25 as result.

Note: The list of functions present in the math library can be referred to here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved