How can I write a MapMapper for the parts map at WithParts class below as mentioned at Custom Mappers (custom Iterables and Maps)
I already tried to use the skeleton available as Custom Mappers page but I can´t make it work. I get a JsonUnsupportedObjectError (converting object to an encodable object faile; _Map len:2) exception at the toJson() line.
import 'package:dart_mappable/dart_mappable.dart';
import 'package:flutter/material.dart';
part 'dart_mappable_mapmapper.mapper.dart';
@MappableClass()
class Part with PartMappable {
final String partID;
late final Offset _value;
Part(this.partID, Offset value) {
_value = value;
}
Offset get value => _value;
}
@MappableClass()
class WithParts with WithPartsMappable {
late final String _id;
late final Map<int, Part> _parts;
WithParts(String id, Map<int, Part> parts) {
_id = id;
_parts = parts;
}
Map<int, Part> get parts => _parts;
String get id {
return _id.toLowerCase();
}
}
void main() {
PartMapper.ensureInitialized();
WithPartsMapper.ensureInitialized();
MapperContainer.globals.use(MapMapper<HashMap>(
<K, V>(Map<K, V> m) => HashMap.of(m),
<K, V>(f) => f<HashMap<K, V>>(),
));
Map<int, Part> parts = Map<int, Part>.from({
1: Part('part1', Offset(1, 0)),
2: Part('part2', Offset(2, 0)),
});
var wp1 = WithParts('id1', parts);
var wp1AsJson = wp1.toJson();
var wp1FromJson = WithPartsMapper.fromJson(wp1AsJson);
assert(wp1 == wp1FromJson);
assert(!identical(wp1, wp1FromJson));
}
Bonus question: do I need a custom mapper for Offset?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745351367a4623852.html
评论列表(0条)