From 22556fd3c42435d190caf2d652b1405e384e0944 Mon Sep 17 00:00:00 2001 From: Vandad Nahavandipoor Date: Sat, 26 Nov 2022 07:41:55 +0100 Subject: [PATCH] Create dart-object-description-using-reflection.dart --- ...t-object-description-using-reflection.dart | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 tipsandtricks/dart-object-description-using-reflection/dart-object-description-using-reflection.dart diff --git a/tipsandtricks/dart-object-description-using-reflection/dart-object-description-using-reflection.dart b/tipsandtricks/dart-object-description-using-reflection/dart-object-description-using-reflection.dart new file mode 100644 index 0000000..9776d63 --- /dev/null +++ b/tipsandtricks/dart-object-description-using-reflection/dart-object-description-using-reflection.dart @@ -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 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(); + final properties = { + 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, + }); +}