如何在String中使用此名称获取属性? [英] How to get a property by this name in String?
问题描述
我想通过名称si字符串格式访问属性.
I want to access to a property by the name si string format.
如果我有这样的课程:
class PrefsState {
String a;
PrefsState({
this.a,
})
我该怎么做?
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test[key]);
当然不起作用.Dart有办法做到这一点吗?
Of course is not working. There is a way to do that in Dart ?
推荐答案
不幸的是,您不能在抖动中使用反射/镜像.您可以做的是乏味的,就是使用地图.
Unfortunately, you cannot use reflection/mirrors in flutter. What you can do, which is tedious, is use maps.
class PrefsState {
String a;
const PrefsState({ this.a, });
dynamic getProp(String key) => <String, dynamic>{
'a' : a,
}[key];
}
在构造函数中构建映射可能更好,但是如果您要使用const构造函数,则必须为此解决.除非您有百万个参数,否则可能不会有太大的不同.然后像这样使用它:
It's probably better to build the map in the constructor, but if you want const constructors then you'll have to settle for this. Likely won't make much of a difference unless you have a million parameters anyway. Then you use it like so:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test.getProp(key));
我认为没有比这麻烦的方法了,但是很想被证明是错误的:-)
I don't think there is a less cumbersome way of doing this, but would love to be proven wrong :-)
这篇关于如何在String中使用此名称获取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!