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:

I've been seeing that the both variable has the same types of data. It's just strings.
Here
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
you are declaring constant values. They will not be changed at runtime, so you know at compile time that the value will always be the same. And thus you can declare the resulting string as const at compile time.
const validConstString = '$aConstNum $aConstBool $aConstString';
Here
var aNum = 0;
var aBool = true;
var aString = 'a string';
you are declaring the variables as var. They can change their values at runtime so you can't say at compile time what will be their value during the lifetime of the application, even if you assign an initial value.
That's why you declare the resulting string as var.
var validString = '$aNum $aBool $aString $aConstList';
Both resulting variables will be string, but the first one will be constant for the whole life of the application, and the second can change if the individual variables change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With