Point class in Dart

The Point class in Dart simplifies the use of two-dimensional positions in programs. The class contains widely-used functions that are used on two-dimensional coordinates and support several useful operations.

svg viewer

Important features

Below is a list of interesting features of the Point class:

  • Point(T x, T y) → Class constructor that takes in numeric coordinates x and y.
  • Point.x and Point.y → Properties used to access the set coordinates.
  • Point.magnitude → Property returns straight line distance between point and origin (0,0).
  • Point.distanceTo(Point<T> otherPoint) → Method returns distance between the point and otherPoint.
  • Point.squaredDistanceTo(Point<T> otherPoint) → Method returns distance squared between the point and otherPoint.
  • Point * num factor → Operator scales point by factor.
  • Point + Point otherPoint → Operator adds point and otherPoint to produce a third point.
  • Point - Point otherPoint → Operator finds the difference between point and otherPoint to produce a third point.
  • Point == dynamic other → Operator returns a bool based on whether or not point and other are equal.

Implementation

The program below delineates the features listed above:

import 'dart:convert';
import 'dart:math'; //Point class is part of this library
void main() {
//The constructor takes in numeric x and y values as coordinates(Point(T x, T y)).
//Instantiating Point variables:
var p1 = Point(20, 40);
var p2 = Point(23.2, 82.8);
var p3 = Point(12, 23);
//Printing the x and y values of p1, p2 and p3:
print("x value of p1: ${p1.x}");
print("y value of p1: ${p1.y}");
print("x value of p2: ${p2.x}");
print("y value of p2: ${p2.y}");
print("x value of p3: ${p3.x}");
print("y value of p3: ${p3.y}");
//Printing the Euclidean distance between the points and origin (0, 0):
print("Magnitude of p1: ${p1.magnitude}");
print("Magnitude of p2: ${p2.magnitude}");
print("Magnitude of p3: ${p3.magnitude}");
//Printing distance between p1 and p3:
print("Distance between p1 and p3: ${p1.distanceTo(p3)}");
//Printing the squared distance between p1 and p3:
print("Squared distance between p1 and p3: ${p1.squaredDistanceTo(p3)}");
//Printing x and y values of p1 scaled up by 3:
Point scaledP1 = p1*3;
print("x value of p1 scaled by 3: ${scaledP1.x}");
print("y value of p1 scaled by 3: ${scaledP1.y}");
//Printing the x and y values of the sum of p1 and p3:
Point sum = p1 + p3;
print("x value of the sum of p1 and p3: ${sum.x}");
print("y value of the sum of p1 and p3: ${sum.y}");
//Printing the x and y values of the difference between p1 and p3:
Point difference = p1 - p3;
print("x value of the difference between p1 and p3: ${difference.x}");
print("y value of the difference between p1 and p3: ${difference.y}");
//Checking if points are equal or not with the == operator
Point p4 = p1;
print("p1 and p3 are equal: ${p1==p3}");
print("p1 and p4 are equal: ${p1==p4}");
}
Copyright ©2024 Educative, Inc. All rights reserved