I am trying to serialize a class so that it can be saven in Shared Prefences. For serialization I use the JsonSerializable package for Flutter.
My generated code looks like this:
class calculation {
List<int>? calcs;
List<int>? results;
List<int>? selectedSpots;
List<double>? linedataX;
List<double>? linedataY;
Map<int, List<int>>? someMap;
calculation({
this.calcs,
this.results,
this.selectedSpots,
this.linedataX,
this.linedataY,
this.someMap,
});
factory calculation.fromJson(Map<String, dynamic> jsonData) {
return calculation(
calcs: jsonData['calcs'].cast<int>(),
results: jsonData['results'].cast<int>(),
selectedSpots: jsonData['selectedSpots'].cast<int>(),
linedataX: jsonData['linedataX'].cast<double>(),
linedataY: jsonData['linedataY'].cast<double>(),
someMap: (jsonData['someMap'] as Map?)?.map(
(k, e) => MapEntry(int.parse(k as String), e as List<int> ),
),
);
}
static Map<String, dynamic> toMap(calculation calc) => {
'calcs': calc.calcs,
'results': calc.results,
'selectedSpots': calc.selectedSpots,
'linedataX': calc.linedataX,
'linedataY': calc.linedataY,
'someMap': calc.someMap?.map((k, e) => MapEntry(k.toString(), e)),
};
The Error only occurs if my map is Map<int, List>?.
Map<int,int>? works fine.
Any Idea how to correctly cast to list?
CodePudding user response:
Try to change this
calcs: jsonData['calcs'].cast<int>(),
results: jsonData['results'].cast<int>(),
selectedSpots: jsonData['selectedSpots'].cast<int>(),
to this:
calcs: jsonData['calcs'].cast<List<int>>(),
results: jsonData['results'].cast<List<int>>(),
selectedSpots: jsonData['selectedSpots'].cast<List<int>>(),
Now casting to a List
CodePudding user response:
Solved it by using a custom object instead of a map.