I've got problems with mappers in Dart which is for me a big problem. I need to get a list of json objects but I want to handle Exceptions, that's why I use Either type as a return of my functions. The only way to handle it and I'm not sure it can work is in arrayListFromJson(json) :
class ItemEntryMapper {
static Either<Exception, ItemEntryModel> fromJson(Map<String, dynamic> json) {
try {
return Right(ItemEntryModel(
id: json['id'] as int,
value: json['value'] as List<String>,
hasError: json['hasError'] as bool,
file: FileWrapperMapper.arrayListFromJson(json['file']).fold(
(Exception exception) => null,
(List<FileWrapperModel> fileWrappers) => fileWrappers),
hasEntryTable: json['hasEntryTable'] as bool,
type: json['type'] as int,
audit: arrayListFromJson(json['audit']).fold(
(Exception exception) => null,
(List<ItemEntryModel> itemEntries) => itemEntries),
auditParentId: json['auditParentId'] as int,
errorFieldName: json['errorFieldName'] as String,
blueAppLaunch:
json['blueAppLaunch'] as List<WorkflowBlueAppLaunchModel>,
workflowBlueAppLaunch:
json['workflowBlueAppLaunch'] as WorkflowBlueAppLaunchModel,
parentWordId: json['parentWordId'] as int,
));
} catch (e) {
return Left(Exception('An error during ItemEntry mapping : $e'));
}
}
static Either<Exception, List<ItemEntryModel>> arrayListFromJson(
Map<String, dynamic> json) {
final list = List<ItemEntryModel>();
final List<dynamic> itemEntries = json['file'];
var result = itemEntries.map((dynamic e) => fromJson(e)).toList();
result.forEach((e) => e.fold(
(Exception exception) => Left<Exception, List<ItemEntryModel>>(
Exception('An error during ItemEntries mapping : $e')),
e.fold((Exception exception) => null, (ItemEntryModel itemEntry) {
list.add(itemEntry);
})));
return Right(list);
}
}
This is weird. I have to use a foreach, then in the foreach a fold, that open a new fold in it second argument... Do you know how to make it efficient (it's really ugly actually) ? Maybe it's because I'm not familiar with this language for the moment.
This whole block only for get a list and handle error.... Thanks
try this
List<YourModel> _jsonArrayToList(List list) {
List<YourModel> _list = [];
for (var i = 0; i < list.length; i++) {
_list.add(YourModel.fromJson(list[i]));
}
return _list;}