Skip to content

Instantly share code, notes, and snippets.

@loicgeek
Last active August 8, 2022 16:30
Show Gist options
  • Save loicgeek/a28eabee41f703eb89a5d737bed40f59 to your computer and use it in GitHub Desktop.
Save loicgeek/a28eabee41f703eb89a5d737bed40f59 to your computer and use it in GitHub Desktop.
import 'dart:math';
import 'package:reflectable/reflectable.dart';
import 'main.reflectable.dart';
const fieldReflector = FieldReflector();
class FieldReflector extends Reflectable {
const FieldReflector()
: super(
typeAnnotationQuantifyCapability,
invokingCapability,
declarationsCapability,
typeRelationsCapability,
metadataCapability,
staticInvokeCapability,
instanceInvokeCapability,
topLevelInvokeCapability,
instanceInvokeCapability,
);
}
@fieldReflector
class User {
String? firstname, lastname;
int? age;
@override
String toString() {
return "firstname:$firstname,lastname:$lastname,age:$age";
}
}
main() {
initializeReflectable();
var results = generate<User>(3);
print(results);
}
fakeType(Type type) {
if (type == int) {
return Random().nextInt(100) + 1;
} else if (type == String) {
return "value${Random().nextInt(100) + 1}";
}
}
List<T> generate<T>([int count = 1]) {
List<T> results = [];
var classMirror = fieldReflector.reflectType(T) as ClassMirror;
for (var i = 0; i < count; i++) {
var t = classMirror.newInstance("", []);
var aInstanceMirror = fieldReflector.reflect(t);
for (var field in classMirror.declarations.values) {
if (field is! VariableMirror) continue;
VariableMirror variableMirror = field;
Type fieldType = variableMirror.type.reflectedType;
var value = fakeType(fieldType);
aInstanceMirror.invokeSetter(variableMirror.simpleName, value);
}
results.add(t as T);
}
return results;
}
@loicgeek
Copy link
Author

loicgeek commented Aug 8, 2022

Installer les dependances reflectable et build_runner (dev) , generer le code: pub run build_runner build et lancer le projet dart main.dart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment