I have a class which has its functions for an instantiated object, but i am aware of other languages which will have helper functions inside the class which are public without defining an object explicitly.
The DART language website seemed like it didnt really address it. In a simple case, it could be something like having a Point class, then having a jsondecoder inside of it which may have some use instead of needing to have other libraries included.
class Point {
int x, y;
Point(this.x, this.y);
Point fromMap(HashMap<String, int> pt){
return new Point(pt["x"]||null, pt["y"]||null);
}
}
that way when i need to use the Point class, i could just say:
Point pt = Point.fromMap({});
I didnt really see any examples as to when I was flipping through classes to make these properly public.
Dart allows to define static member on a class. In your case:
class Point {
int x, y;
Point(this.x, this.y);
static Point fromMap(Map<String, int> pt) {
return new Point(pt["x"], pt["y"]);
}
}
It's worth to note that you can also use named constructor and/or factory constructor :
class Point {
int x, y;
Point(this.x, this.y);
// use it with new Point.fromMap(pt)
Point.fromMap(Map<String, int> pt) : this(pt["x"], pt["y"]);
// use it with new Point.fromMap2(pt)
factory Point.fromMap2(Map<String, int> pt) => new Point(pt["x"], pt["y"]);
}
The given example is perhaps not the best as the desired result is a new Point
. Named constructors - as Alexandre says in his answer - are the preferred solution in the case.
Perhaps a better example (but still kinda artificial) would be:
library Points;
class Point {
...
/// Return true if data in pt is valid [Point] data, false otherwise.
bool isValidData(HashMap<String, int> pt) { ... }
}
In languages without first-class function (e.g., Java), a static method would be proper. Dart supports this also.
class Point {
...
/// Return true if data in pt is valid [Point] data, false otherwise.
static bool isValidData(HashMap<String, int> pt) { ... }
}
As Dart has first class functions, a function defined in the library may be a better choice.
library Points;
bool isValidPointData(HashMap<String, int> pt) { ... }
class Point {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With