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

Mid*_*lai 3 compile-time-constant constant-expression dart

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

请看一下这段代码:

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
  );
}
Run Code Online (Sandbox Code Playgroud)

错误:

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(
        ^
Run Code Online (Sandbox Code Playgroud)

该列表包含常量 Object,那么为什么常量评估失败呢?这不应该是分析器的问题吗?我错过了什么吗?

谢谢。

lrn*_*lrn 5

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

因此,aL[0]它根本就不是一个有效的编译时常量表达式。

一个可能的解决办法可能是使其b2不恒定!