【问题标题】:Getting and setting class attributes in Dart / Flutter在 Dart / Flutter 中获取和设置类属性
【发布时间】:2021-03-08 13:12:15
【问题描述】:

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

示例类:

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

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

}

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

【问题讨论】:

    标签: flutter class dart


    【解决方案1】:

    在您的代码示例中,您将ageheightweight 定义为公共。因此,您不需要定义 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 不支持。

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      相关资源
      最近更新 更多