Incomprehensible behavior of string expressions in Dart

2138 views dart

Today I decide to start learning Dart Language and I started from Tour where there is an example:

// These work in a const string.
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';

// These do NOT work in a const string.
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];

const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';

and text:

Literal strings are compile-time constants, as long as any interpolated expression is a compile-time constant that evaluates to null or a numeric, string, or boolean value.

My question is connected with last line of the code. I've been reading the text a few times but I couldn't understand why a result of the expression ('$aNum $aBool $aString $aConstList') can't be assigning to const variable. But if I change the code like that:

const validConstString = '$aConstNum $aConstBool $aConstString';
var validString = '$aNum $aBool $aString $aConstList';

It'll be worked. What's different between these interpolation expressions? I've tried to look at results via debugger:

enter image description here

I've been seeing that the both variable has the same types of data. It's just strings.

answered question

1 Answer


Because var aNum = 0; is not a const value, you can't use it in string interpolation for another const value const validConstString.

posted this

Have an answer?


Please login first before posting an answer.