flutter Text exception - expression is not a valid compile-time constant
Constants (i.e. const
) in Dart are compile-time, that is, they must not rely on the runtime of your application in anyway, and can only be simple side-effect free constructor invocations (i.e. const
constructors) or literals like strings, numbers, and lists/maps.
For example, this is a compile-time string:
const version = 'v1.0.0';
And I could use it below:
const Text(version)
Dart supports limited expressions as well, as compile-time constants:
const Text('My version is: $version')
However in your example, text
is not a compile-time constant.
Lets view this through a simpler example, called showMyName
:
Widget showMyName(String name) => const Text(name);
This will get an identical error to what you saw, because we're trying to create a compile-time constant Text
from a runtime provided value (the argument name
). Of course, we don't need Text
to be a compile-time constant. You can simply use new
:
Widget showMyName(String name) => new Text(name);
In future versions of Dart (with --preview-dart-2
), you can omit new
:
Widget showMyName(String name) => Text(name);
XoXo
Updated on December 04, 2022Comments
-
XoXo over 1 year
I'm trying to understand the
List
example in flutter_gallery. My approach is to simplify the `` code by refactoring into (my project).I'm seeing a breaking change in this commit
I/flutter (14712): 'file:///Users/hong/Flutter/github/flutter_gallery_material_list/lib/main.dart': error: line 54: I/flutter (14712): expression is not a valid compile-time constant I/flutter (14712): const Text t = const Text(text);
The source code starting line 53 is:
MergeSemantics _mergeSemanticsOf(String text, _MaterialListType listType) { const Text t = const Text(text); //const Text t = const Text('we want a variable here'); return new MergeSemantics( child: new ListTile( dense: true, title: t, trailing: new Radio<_MaterialListType>( value: listType, groupValue: _itemType, onChanged: changeItemType, )), ); }
I can only make it compile with something like:
const Text t = const Text('we want a variable here');
.I understand what the exception says, but wonder if there is a way to pass a variable to Text().
This is the exception popup (in a red box) in VSCode:
And this is the exception on an Android phone (Samsung S7)
A search on Stackoverflow shows this, which looks not related to my question.
-
XoXo about 6 yearsthanks for the detailed explanation. i fixed the issue by using
Text t = new Text(text);
per your suggestions. the commit is here