Dart:持续评估错误。无法在常量表达式中调用方法“[]”

Dart: Constant evaluation error. The method '[]' can't be invoked in a constant expression

我在不断评估时遇到错误。

请看一下这段代码:

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(
        ^

列表包含常量对象,那么为什么常量求值失败?这不应该是分析器的问题吗?我错过了什么吗?

谢谢。

常量表达式只能构建数据,不能解构它。你不能在常量对象上调用任何方法,除了少数对数字的操作(和 String.length,这也会创建一个数字)。

因此,aL[0] 根本不是有效的 compile-time 常量表达式。