A stateless widget receives its data as a parameter. In the data, there is an identifier. I would like to use the identifier as the widget key. Is it possible?
I wrote something like that but the compiler refuses:
class ItemData {
final int id;
final String label;
const ItemData({
required this.id,
required this.label,
})
}
class MyItemInAList extends StatelessWidget {
final ItemData data;
const MyItemInAList({required this.data})
: super(key: ObjectKey(data.id)); // ← Error: Invalid constant value
@override
Widget build(BuildContext context) {
// …
}
}
CodePudding user response:
Remove the const modifier before MyItemInAList, in this case the constructor can't be constant.
ObjectKey will need an object as a parameter, like ObjectKey(data). If you need the id, it might be better to use ValueKey(data.id), maybe adding some prefix to it.
