gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:45:51 27 4
gpt4 key购买 nike

我有一个具有不可变属性 int id 的类。
如何将 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'. this.id=id; ^^ hey.dart:10:10: Error: The setter 'id' isn't defined for the class 'Hey'. - 'Hey' is from 'hey.dart'. Try correcting the name to the name of an existing setter, or defining a setter or field named 'id'. this.id=id; ^^



我认为 const 或 final 字段属性不需要 setter 。
API 不清楚如何处理这个问题。

最佳答案

来自 Dart language tour :

Note: Instance variables can be final but not 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.



初始化列表部分说:

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)');
}


所以一般的方法是通过初始化列表。

如上所述,您还可以在变量声明时进行初始化:

class Foo {
final x = 42;
}

或者可以通过构造函数参数初始化它们:

class Foo {
final x;

Foo(this.x);
}

尽管这些其他方法可能并不总是适用。

关于dart - 如何在 Dart 构造函数中设置 final/const 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com