-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create dart-object-description-using-reflection.dart
- Loading branch information
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
67 changes: 67 additions & 0 deletions
67
...ks/dart-object-description-using-reflection/dart-object-description-using-reflection.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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, | ||
}); | ||
} |