flutter - 在 Dart / Flutter 中获取和设置类属性
问题描述
我想列出一个类的属性并设置它们。例如,在 ListView 中,当我点击某个属性的值时,我想将其增加 1。
示例类:
class Person {
int age;
int height;
int weight;
Person({
this.age,
this.height,
this.weight,
});
}
是否可以在不为每个属性编写 getter 和 setter 函数的情况下列出和设置这些值?
解决方案
在您的代码示例中,您将 、 和 定义age
为height
公共weight
的。因此,您不需要定义 getter 和 setter。您可以直接增加和减少它们的值。
void main() {
final a = Person(age: 25, height: 210, weight: 90);
a.age++;
a.height++;
a.weight++;
print(a);
// This person is 26 years old, 211cm tall and weights 91kg
}
class Person {
int age;
int height;
int weight;
Person({
this.age = 0,
this.height = 0,
this.weight = 0,
});
toString() => 'This person is $age years old, ${height}cm tall and weights ${weight}kg';
}
但是,如果稍后您依赖状态相等来重建 Widget,您可能会遇到改变对象的问题。最好将您的 State 对象处理为不可变的。
然后,关于列出值,如果您提到[dart:mirrors][1]
,Flutter 不支持它。
推荐阅读
- git - Shell:Git 存储库创建脚本不向上游推送远程
- amazon-web-services - 带有 Cognito 正确方法的 AWS Lambda
- php - 如何从内部键和值与第一个数组匹配的第二个数组中找到数组键?
- amazon-web-services - AWS Lightsail 数据库是否会受到突增性能的影响?
- php - 将控制器属性共享给模型方法 - laravel
- java - 如何使用 EJB 实现永久后台进程?
- excel - 如何将宏数据输入目标设置为列中的下一个空白单元格?
- reactjs - 如何从 fullcalendar 的 eventClick 中访问 JSX 函数
- excel - 使用MATLAB通过ActiveX协议将String值写入Excel电子表格..发现问题
- reactjs - 单击按钮时如何修复 onSubmit 函数不显示状态?