Skip to content

Instantly share code, notes, and snippets.

@gerardsimons
Created February 25, 2021 13:43
Show Gist options
  • Save gerardsimons/40fe496e9bfe9759921bd5f86fdcf3c0 to your computer and use it in GitHub Desktop.
Save gerardsimons/40fe496e9bfe9759921bd5f86fdcf3c0 to your computer and use it in GitHub Desktop.
dynamic getters for class based on Map and noSuchMethod
class QueryMap<T> {
Map<String,T> _data;
QueryMap(Map<String,T> data) {
_data = Map<String,T>();
data.forEach((k, v) => _data[new Symbol(k).toString()] = v);
}
dynamic noSuchMethod(Invocation invocation) {
if (invocation.isGetter) {
var ret = _data[invocation.memberName.toString()];
if (ret != null) {
return ret;
} else {
super.noSuchMethod(invocation);
}
}
if (invocation.isSetter) {
_data[invocation.memberName.toString().replaceAll('=', '')] =
invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
void main() {
dynamic qaueryMap = new QueryMap({"ecg":10.0});
print(qaueryMap.ecg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment