In Dart, I can override the toString
method to change the string content returned by an object when it is used as a string.
I need to change the object’s behavior when it is used as a double.
I would like to achieve the same result from this C++ code in Dart:
class Value {
private:
double value;
Color color;
public:
Value(double value, Color color) : value(value), color(color) {}
operator double() const {
return value;
}
};
Meaning that I would be able to use an object from the class Value
like this:
Value value = const Value(value: 13.0, color: Colors.blue);
double a = value + 3; // a = 16.0
double b = value - 3; // b = 10.0
double c = value; // c = 13.0
2
Answers
To achieve a similar result, you could define the addition operator
+
and the subtraction-
operator of theValue
class:Your
main.dart
would then become:you can get similar functionality by defining methods in your class to perform these operations.