I want to make a flexible json decoding function that takes the response body from an api and converts it into object instances using the factory function .fromJson().
I also want the function to be Generic so that it can accept every element that has a factory method .fromJson()
For generatic the code i use JsonSerializable a package suggested in the flutter guides so i hope that's not the problem.
This is the abstract class that decodable objects have to implement:
abstract class WireObject {
WireObject.fromJson(Map<String,dynamic> json);
}
This is an example object:
import 'package:iregistro_flutter/core/models/enums/absence_type.dart';
import 'package:iregistro_flutter/core/models/interfaces/wire_object.dart';
import 'package:json_annotation/json_annotation.dart';
part 'absence_wire.g.dart';
@JsonSerializable()
class Absence implements WireObject {
DateTime date;
String id;
bool justified;
AbsenceType type;
Absence({
required this.date,
required this.justified,
required this.id,
required this.type,
});
@override //idk if i need to override the method
factory Absence.fromJson(Map<String, dynamic> json) => _$AbsenceFromJson(json);
}
And this is my function to decode json into object.
List<T> parseListOfObjects<T extends WireObject>(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
final documents = parsed
.map((json) => T.fromJson(json))
.toList();
return documents;
}
Thanks for the help, i'm fairly new to flutter and i apologize in advance if i had made a silly mistake.