[英]Flutter Dart - dynamically get a property of a class
I would like to get the property of a class by passing a String name.我想通过传递字符串名称来获取类的属性。 How can I do that?
我怎样才能做到这一点?
class A {
String fName ='Hello';
}
main() {
A a = A();
String var1='fName'; // name of property of A class
print (a.fName); // it is working fine
print (a.$var1); // it is giving error that no getter in A class. but I want to pass var1 and automatically get the associate property
}
Further to Suman's answer I recommend exposing a method that converts the object to a map and retrieves the property if it's there.除了苏曼的回答,我建议公开一种方法,该方法将对象转换为地图并检索该属性(如果存在)。
For example:例如:
class Person {
String name;
int age;
Person({this.age, this.name});
Map<String, dynamic> _toMap() {
return {
'name': name,
'age': age,
};
}
dynamic get(String propertyName) {
var _mapRep = _toMap();
if (_mapRep.containsKey(propertyName)) {
return _mapRep[propertyName];
}
throw ArgumentError('propery not found');
}
}
main() {
Person person = Person(age: 10, name: 'Bob');
print(person.name); // 'Bob'
print(person.get('name')); // 'Bob'
print(person.get('age')); // 10
// wrong property name
print(person.get('wrong')); // throws error
}
A quick workaround would be,一个快速的解决方法是,
void main() {
String var1='name';
String var2='age';
Info info= Info(name:"Suman", age:4);
final json=info.toJson();
print("NAME = ${json[var1]}");
print("AGE = ${json[var2]}");
}
class Info {
String name;
int age;
Info({this.name, this.age});
Info.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
return data;
}
}
Hope this helps.希望这可以帮助。 Cheers.
干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.