我正在使用 Dart 2.1.0 在 Flutter 中编程,遇到这种情况:
mixin Salt {
final int pinches; // Immutable, and I want to delay initialization.
// Cannot declare constructors for mixin
}
class Meat with Salt {
Meat(int pinches) ... // How to initialize it?
}
Salt
没有构造函数,所以我不能使用初始化列表。 pinches
是 final
,所以我无法在 Meat
的构造函数中设置它。
我不想让 Salt
成为一个类,因为 Meat
可能需要从其他东西扩展。
我想让 pinches
保持不变。
有什么办法吗?提前致谢。
最佳答案
您可以将 mixin 的声明更改为:
mixin Salt {
int get pitches;
}
然后在实现类里面定义字段
class Meat with Salt {
final int pitches;
Meat(this.pitches);
}
关于dart - 如何在 Dart 中初始化 mixin 的不可变数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54166892/