flutter pub run build_runner build gives an error on geoPoint. Error says: To support the type GeoPoint
you can: Use JsonConverter
.
How can I implement it?
class
...
@JsonSerializable()
class Person{
late final String name;
final List<Location> location;
Person(
{required this.uid,
required this.name,
required this.location});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
@JsonSerializable()
class Location {
String name;
GeoPoint geoPoint;
Location({required this.name, required this.geoPoint});
factory Location.fromJson(Map<String, dynamic> json) =>
_$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationToJson(this);
}
CodePudding user response:
Example for Colors :
@JsonSerializable()
class Line {
Line({required this.name, required this.color});
factory Line.fromJson(Map<String, dynamic> json) => _$LineFromJson(json);
String name;
@ColorSerializer()
Color color;
Map<String, dynamic> toJson() => _$LineToJson(this);
}
class ColorSerializer implements JsonConverter<Color, int> {
const ColorSerializer();
@override
Color fromJson(int json) => Color(json);
@override
int toJson(Color color) => color.value;
}
Your Code should be something like this:
@JsonSerializable()
class Line {
Line({required this.name, required this.color});
factory Line.fromJson(Map<String, dynamic> json) => _$LineFromJson(json);
String name;
@GeoPointSerializer()
GeoPoint geoPoint;
Map<String, dynamic> toJson() => _$LineToJson(this);
}
class GeoPointSerializer implements JsonConverter<GeoJson, List<int,int>> {
const GeoPointSerializer();
@override
GeoPoint fromJson(List<int,int> json) => GeoPoint(x:json[0],json[1]);
@override
List<int,int> toJson(GeoPoint geoPoint) => [geoPoint.x,geoPoint.y];
}