问题描述
我在进行持续评估时出错。
请看一下这段代码:
class A {
final num a;
const A(this.a);
}
class B {
final A a;
const B(this.a);
}
main() {
const a = A(12);
const b = B(a); // this works fine
// I believe everything inside a const List is considered constant,// please correct me if that is wrong
const aL = [ A(12),A(13) ]; // [ a,A(13) ] will not work either
const b2 = B(
aL[0],// here the error is happening
);
}
错误:
lib/logic/dartTest.dart:22:14: Error: Constant evaluation error:
const b2 = B(
^
lib/logic/dartTest.dart:23:7: Context: The method '[]' can't be invoked on '<A>[A {a: 12},A {a: 13}]' in a constant expression. - 'A' is from 'package:t_angband/logic/dartTest.dart' ('lib/logic/dartTest.dart').
aL[0],^
lib/logic/dartTest.dart:22:9: Context: While analyzing:
const b2 = B(
^
列表包含常量Object,那么为什么常量求值失败?这不应该是分析仪问题吗?我想念什么吗?
谢谢。
解决方法
常量表达式只能 build 数据,不能解构它。除了对数字执行的少数操作(以及String.length
,它还会创建一个数字),您无法在常量对象上调用任何方法。
因此,aL[0]
根本不是有效的编译时常量表达式。