I want to declare, but not define a factory constructor in an abstract class.
In my case, I want to create a method that accepts any class that implements a St
As suggested in the accepted answer, I ended up creating a Serializer type that got implemented by a serializer for each class:
Turns out, this has several benefits over just having toJson/fromJson on the classes directly:
String or Flutter's Color, where you can't just add a fromColor constructor.Code example:
class Fruit {
Fruit(this.name, this.color);
final String name;
final String color;
}
// in another file
class FruitSerializer extends Serializer {
Map toJson(Fruit fruit) {
return ...;
}
Fruit fromJson(Map data) {
return Fruit(...);
}
}
An then also pass the serializer to the code that needs it:
someMethod(Serializer serializer, T value) {
...
}
someMethod(FruitSerializer(), someFruit);
final fruit = recreateFruit(FruitSerializer());
Obviously, you can't pass an object that can't be serialized to the code, because the method expects a Serializer.