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