Created
February 25, 2021 13:43
-
-
Save gerardsimons/40fe496e9bfe9759921bd5f86fdcf3c0 to your computer and use it in GitHub Desktop.
dynamic getters for class based on Map and noSuchMethod
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
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