How to convert an Object type to a Map type (array) in Dart, so the variables become key/value pairs?
/**
* Uses refection (mirrors) to produce a Map (array) from an object's
* variables. Making the variable name the key, and it's value the
* value.
*/
Map objectToMap(Object object)
{
// Mirror the particular instance (rather than the class itself)
InstanceMirror instanceMirror = reflect(object);
Map dataMapped = new Map();
// Mirror the instance's class (type) to get the declarations
for (var declaration in instanceMirror.type.declarations.values)
{
// If declaration is a type of variable, map variable name and value
if (declaration is VariableMirror)
{
String variableName = MirrorSystem.getName(declaration.simpleName);
String variableValue = instanceMirror.getField(declaration.simpleName).reflectee;
dataMapped[variableName] = variableValue;
}
}
return dataMapped;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With