Search code examples
dartcompile-time-constantconstant-expression

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


I am getting an error on constant evaluation.

please take a look at this code:

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
  );
}

Error:

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

The list contains constant Object, then why the constant evaluation is failing? Shouldn't this be an analyzer issue? Am I missing something?

Thankyou.


Solution

  • Constant expressions can only build data, it cannot deconstruct it. You cannot call any methods on the constant objects except a handful of operations on numbers (and String.length, which also creates a number).

    So, aL[0] is simply not a valid compile-time constant expression.

    A possible fix may be to make b2 not constant!