dart - const 构造函数创建非常量类对象?
问题描述
以下代码出现错误Error: Cannot invoke a non-'const' constructor where a const expression is expected.
:
class TestConst {
final num x;
final num y;
TestConst(this.x, this.y);
}
void main() {
TestConst myconst1 = const TestConst(1,2);
TestConst myconst2 = const TestConst(1,2);
print(identical(myconst1, myconst2));
}
而以下没有,并且当确实只有 const-constructor时奇怪地identical(myconst1, myconst2)
返回?:false
TestConst
class TestConst {
final num x;
final num y;
const TestConst(this.x, this.y);
}
void main() {
TestConst myconst1 = TestConst(1,2);
TestConst myconst2 = TestConst(1,2);
print(identical(myconst1, myconst2));
}
解决方案
const
on a constructor 意味着构造函数可以创建一个const
对象(如果调用站点选择加入并且所有构造参数也是const
),而不是它只创建const
对象。
语言之旅确实提到了这一点(但没有详细说明):
常量构造函数并不总是创建常量。有关详细信息,请参阅使用构造函数部分。
...
一些类提供常量构造函数。要使用常量构造函数创建编译时常量,请将
const
关键字放在构造函数名称之前:
如果您想知道为什么声明为 with 的构造函数在调用时const
仍需要显式指定,请参阅: Dart:使用 const 构造函数有缺点吗?const