所以我看到这样的代码:
class Whatever {
final String name;
const Whatever(this.name);
}
通过使用
const
标记构造函数这一事实会发生什么变化?它有什么作用吗?我读过这样的话:
Use const for variables that you want to be compile-time constants. If the const variable is at the class level, mark it static const. (Instance variables can’t be const.)
但是对于类构造函数似乎没有意义。
最佳答案
static const someName = const Whatever()
; 如果该类没有const构造函数,则不能用于初始化常量字段。我认为在构造函数中指定它是有意义的。您仍然可以在运行时使用
new Whatever()
创建实例或添加工厂构造函数。也可以看看
“旧样式”(仍然有效)枚举是如何使用const的一个很好的例子
https://stackoverflow.com/a/15854550/217408
关于dart:将类构造函数标记为const的含义是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28982231/