提问人:Frank Zeng 提问时间:9/6/2023 更新时间:9/6/2023 访问量:56
Flutter Dart - 动态设置类的属性
Flutter Dart - dynamically set a property of a class
问:
我想通过传递变量 String name 来设置类的属性。我该怎么做?
类似于 @Chad Lamb 提供的 get 方法
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
}
我尝试了很多方法,但还没有成功。
答:
0赞
Dharam Budh
9/6/2023
#1
请尝试以下代码:
try {
print(person.get("wrong"));
} on Error catch (e) {
print(e);
}
输出:
Invalid argument(s): propery not found
评论
package:reflectable
)。否则,如果你需要一些动态的东西,那么使用一个或,就像你已经在做的那样。Map<String, Object?>
Map<String, dynamic>