I’d like to provide an alternative constructor for my Circe class where the center and radius are calculated from 3 points. But I cannot find a way to store the calculated center to the temporal variable and pass it to both final fields. Calling _getCenter twice works, but this approach is suboptimal. Is there a more efficient way?
import 'dart:math';
class Circle {
final Point center;
final double radius;
Circle(this.center, this.radius);
Circle.fromPoints(Point p1, Point p2, Point p3)
: center = _getCenter(p1, p2, p3),
radius = _getCenter(p1, p2, p3).distanceTo(p1);
static Point _getCenter(Point p1, Point p2, Point p3) {
...
}
>Solution :
You could make use of a factory constructor:
import 'dart:math';
class Circle {
final Point center;
final double radius;
Circle(this.center, this.radius);
factory Circle.fromPoints(Point p1, Point p2, Point p3) {
final center = _getCenter(p1, p2, p3);
final radius = center.distanceTo(p1);
return Circle(center, radius);
}
static Point _getCenter(Point p1, Point p2, Point p3) {
...
}
}
The point of such constructor is to behave like a constructor but does not create any object instance automatically. You must then return an object that is compatible with the class the factory constructor is part of.