I am using the following dart packages (json_annotation, json_serializable, build_runner) to serialize/de-serialize json according to this page.
This is my code:
import 'package:json_annotation/json_annotation.dart';
part 'car_type.g.dart';
@JsonSerializable()
class CarType {
final int id;
@JsonKey(name: 'type_label')
final String label;
final String description;
CarType(this.id, this.label, this.description);
factory CarType.fromJson(Map<String, dynamic> json) =>
_$CarTypeFromJson(json);
factory List<CarType> CarType.fromJsonList(dynamic jsonArray){
final list = jsonArray as List;
final carTypesList = list.map((i) => CarType.fromJson(i));
return carTypesList;
}
}
So with the factory List<CarType> CarType.fromJsonList(dynamic jsonArray) I want to pass a json array to get back a list of CarType objects. However I'am getting a couple of compiler errors namely:
Any idea what is going on?
factory List<CarType> CarType.fromJsonList(dynamic jsonArray){
You can't specify a return type for a constructor.
The return type is always the same as the class the constructor is member of.
Just replace factory with static and you should be fine,
except json_serializable expects a factory constructor, then you need to remove the return type and find another approach to get the List.
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