简体   繁体   English

如何在Dart构造函数中设置final / const属性

[英]How to set final/const properties in Dart constructor

I have a class with an immutable property, int id. 我有一个具有不可变属性的类,int id。 How do I pass the value of id to the constructor? 如何将id的值传递给构造函数?

class Hey
{
  var val;
  final int id;
  Hey(int id,var val)
  {
    this.id=id;
    this.val=val;
  }
}

void main()
{
  Hey hey=new Hey(0,1);
}

hey.dart:10:10: Error: Setter not found: 'id'. hey.dart:10:10:错误:未找到Setter:'id'。 this.id=id; this.id = ID; ^^ hey.dart:10:10: Error: The setter 'id' isn't defined for the class 'Hey'. ^^ hey.dart:10:10:错误:没有为类'嘿'定义setter'id'。 - 'Hey' is from 'hey.dart'. - '嘿'来自'hey.dart'。 Try correcting the name to the name of an existing setter, or defining a setter or field named 'id'. 尝试将名称更正为现有setter的名称,或者定义名为“id”的setter或字段。 this.id=id; this.id = ID; ^^ ^^

I don't think a setter is required for a const or final field property. 我认为const或final字段属性不需要setter。 The API is not clear on how to handle this. API尚不清楚如何处理这个问题。

From the Dart language tour : Dart语言之旅

Note: Instance variables can be final but not const . 注意:实例变量可以是final但不是const Final instance variables must be initialized before the constructor body starts — at the variable declaration, by a constructor parameter, or in the constructor's initializer list . 最终实例变量必须在构造函数体启动之前初始化 - 在变量声明,构造函数参数或构造函数的初始化列表中

And the section on initializer lists says: 初始化列表中的部分说:

Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. 除了调用超类构造函数之外,还可以在构造函数体运行之前初始化实例变量。 Separate initializers with commas. 用逗号分隔初始化程序。

 // Initializer list sets instance variables before // the constructor body runs. Point.fromJson(Map<String, num> json) : x = json['x'], y = json['y'] { print('In Point.fromJson(): ($x, $y)'); } 

So the general way is through initialization lists. 所以一般的方法是通过初始化列表。

As mentioned above, you also can initialize at variable declaration: 如上所述,您还可以在变量声明处初始化:

class Foo {
  final x = 42;
}

or can initialize them by a constructor parameter: 或者可以通过构造函数参数初始化它们:

class Foo {
  final x;

  Foo(this.x);
}

although those other approaches might not always be applicable. 虽然那些其他方法可能并不总是适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM