飞镖:常数评估错误方法“ []”不能在常量表达式中调用

问题描述

我在进行持续评估时出错。

请看一下这段代码:

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]根本不是有效的编译时常量表达式。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...