/
simple_mapper_example.dart
56 lines (50 loc) · 1.47 KB
/
simple_mapper_example.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import 'package:simple_mapper/simple_mapper.dart';
import 'models/company_a.dart';
import 'models/company_b.dart';
import 'models/employee_a.dart';
import 'models/employee_b.dart';
void main() {
var now = DateTime.now();
var mapper = Mapper()
.addMap<CompanyB, CompanyA>(
(source, mapper, [params]) => CompanyB(
id: source.id,
name: source.name,
// Use the mapper to map children.
employees: source.employees
?.map(
(employee) => mapper.map<EmployeeB, EmployeeA>(employee, {
'companyId': source.id,
}),
)
.toList(),
),
)
.addMap<EmployeeB, EmployeeA>(
(source, mapper, [params]) => EmployeeB(
id: source.id,
// EmployeeA doesn't have companyId so we pass it through params.
companyId: params!['companyId'] ?? 0,
name: source.name,
startDate: source.startDate,
timeEmployed: source.startDate == null || source.endDate == null
? null
: source.endDate!.difference(source.startDate!),
),
);
var companyA = CompanyA(
id: 1,
name: 'ABC',
employees: <EmployeeA>[
EmployeeA(
id: 1,
name: 'John Smith',
startDate: now.subtract(Duration(days: 30)),
endDate: now,
)
],
);
print(companyA);
print('mapped to');
print(mapper.map<CompanyB, CompanyA>(companyA));
}