首页 > 解决方案 > 在 Dart / Flutter 中获取和设置类属性

问题描述

我想列出一个类的属性并设置它们。例如,在 ListView 中,当我点击某个属性的值时,我想将其增加 1。

示例类:

class Person {
int age;
int height;
int weight;

Person({
this.age,
this.height,
this.weight,
});

}

是否可以在不为每个属性编写 getter 和 setter 函数的情况下列出和设置这些值?

标签: flutterclassdart

解决方案


在您的代码示例中,您将 、 和 定义ageheight公共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 不支持它。


推荐阅读