I'm trying to use a variable in Text Widget, it says Invalid const value, so, I need to use a const, but I'm using Text Widget in a dynamic way. Is there a way to use a Text with variables? or is there another Widget that I could use?
I have something like this:
class PlaceCardState extends StatelessWidget {
PlaceCardState(this._placeCard);
Place _placeCard;
@override
Widget build(BuildContext context) {
return ListTile(
leading: const Icon(Icons.album),
title: Text(_placeCard.title),
subtitle: const Text('Come and dance tonight!'),
);
}
}
place.dart
class Place {
Place([this.title = '', this.description = '', this.image='', this.value=0.0]);
String title;
String description;
String image;
double value;
}
I get this issue:
![](https://www.manongdao.com/static/images/pcload.jpg)
Change this:
const ListTile(
leading: const Icon(Icons.album),
title: Text(_placeCard.title),
subtitle: const Text('Come and dance tonight!'),
);
into this:
const ListTile(
leading: const Icon(Icons.album),
title: const Text(_placeCard.title),
subtitle: const Text('Come and dance tonight!'),
);
Since in your screenshot ListTile
is a constant then all the properties need to be constant also, therefore add const
before Text(_placeCard.title),
Const
will be assumed for Icon
and Text
, as they have to be constant, so that the ListTile
can be constant as a whole.
So it's the same to write:
const ListTile(
leading: const Icon(Icons.album),
title: const Text(_placeCard.title),
subtitle: const Text('Come and dance tonight!'),
);
as
const ListTile(
leading: Icon(Icons.album),
title: Text(_placeCard.title),
subtitle: Text('Come and dance tonight!'),
);
But you seem to confuse the meaning of const
anyway, as this probably won't work in your application.
From news.dartlang.org,
"const" has a meaning that's a bit more complex and subtle in Dart.
const modifies values. You can use it when creating collections, like
const [1, 2, 3], and when constructing objects (instead of new) like
const Point(2, 3). Here, const means that the object's entire deep
state can be determined entirely at compile time and that the object
will be frozen and completely immutable
so that means that you could say
const ListTile(
leading: Icon(Icons.album),
title: Text("foo"),
subtitle: Text('Come and dance tonight!'),
);
but not create that Object constant while running the application, as you don't have all data at compile-time.
You should just not use const and then it should be alrighto.