-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathdart-object-description-using-reflection.dart
67 lines (61 loc) · 1.37 KB
/
dart-object-description-using-reflection.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
57
58
59
60
61
62
63
64
65
66
67
// 🎥 YouTube https://youtube.com/c/vandadnp
// 🐦 Twitter https://twitter.com/vandadnp
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
import 'dart:mirrors';
void main(List<String> args) {
print(
Person(
name: 'John',
age: 30,
),
);
print(
House(
address: '123 Main St',
rooms: 6,
),
);
}
mixin HasDescription {
@override
String toString() {
final reflection = reflect(this);
final thisType = MirrorSystem.getName(
reflection.type.simpleName,
);
final variables =
reflection.type.declarations.values.whereType<VariableMirror>();
final properties = <String, dynamic>{
for (final field in variables)
field.asKey: reflection
.getField(
field.simpleName,
)
.reflectee
}.toString();
return '$thisType = $properties';
}
}
extension AsKey on VariableMirror {
String get asKey {
final fieldName = MirrorSystem.getName(simpleName);
final fieldType = MirrorSystem.getName(type.simpleName);
return '$fieldName ($fieldType)';
}
}
class Person with HasDescription {
final String name;
final int age;
Person({
required this.name,
required this.age,
});
}
class House with HasDescription {
final String address;
final int rooms;
House({
required this.address,
required this.rooms,
});
}