10

Why there is an error, when the foo is already a const value?

const foo = const [10, 20];
const bar = foo[0] * 2; // error: const variables must be initialized with a constant value. 
asked Oct 14, 2019 at 9:08

1 Answer 1

17

That's because while the variables used to create your second constant are constants, you also used the operator [] – which is not compile-time constant.

So while you can do:

const a = 42;
const b = a * 3;

you cannot do:

const array = [42];
const b = a[0];
answered Oct 14, 2019 at 9:52
Sign up to request clarification or add additional context in comments.

1 Comment

Its giving the same error for const String name = 1.toString();? Here 1 is a constant but dart is still its generating Const variables must be initialized with a constant value. Try changing the initializer to be a constant

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.