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:
Random: This class contains methods to generate random bool, int, or double values.
Point: This class is used for representing two-dimensional(x,y) positions.
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.
MutableRectangle: This class is the same as the
Rectangleclass except that the properties of theMutableRectangleare mutable whereas the properties of theRectangleclass 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 classesvar 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 booleanvar randomBool = Random().nextBool();print('Random booleanValue : ${randomBool}');// get square root of a nummbervar sqrtOf25 = sqrt(25);print('Square root of 25 : ${sqrtOf25}');// get maximum of two nnumbersvar maxVal = max(25, 22);print(' max(25, 22) : ${maxVal}');}
Explanation
Line 1: Imports the
mathlibrary.Line 5: Creates a new object for the
Pointclass. We set the 10 and 20 as the value forxandyproperty respectively.Line 9: Creates a new object for the
Pointclass. We set 0 as the value for theleftandtopproperty and 10 as the value for therightandbottomproperty.Line 13: Uses the
nextIntmethod ofRandomclass 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
nextBoolmethod ofRandomclass. It will return a random bool value(true or false).Line 21: Uses the
sqrtfunction with 25 as an argument. This method will return the square root of 25 as a double value.Line 25: Uses the
maxfunctions 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