dart - 如何在 Dart 中初始化 mixin 的不可变数据?

标签 dart flutter mixins final

我正在使用 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 没有构造函数,所以我不能使用初始化列表。 pinchesfinal,所以我无法在 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/

相关文章:

firebase - 无法安装 Firebase 消息包

flutter - 有没有办法使用 flutter 检测pdf中的触摸?

polymer - 如何设置 paper 下拉菜单的样式(如何使用 mixins?)

callback - 如何从 flutter 中的状态类访问根类中的方法

Flutter (Dart) : Split the screen into 6 sections, 每个在中心有一个角

android - Flutter:当其他小部件可用时,ListView的高度正在减小

Dart:不带扩展的 mixin 组合

css - 在 SASS 混入中使用椭圆形边界半径

firebase - 无法从方法 'User?' 返回类型为 '_userFromFirebaseUser' 的值,因为它的返回类型为 'User'

flutter - 位置欺骗器破坏了地理定位器?