I am trying to pass an itemBuilder
to another widget. Here's the isolated problematic widget
to reproduce the error:
class TestWidget<ITEM> extends StatefulWidget {
final List<ITEM> items;
final Widget Function(int index, ITEM item) itemBuilder;
const TestWidget({
Key? key,
required this.items,
required this.itemBuilder,
}) : super(key: key);
@override
_TestWidgetState createState() => _TestWidgetState<ITEM>();
}
class _TestWidgetState<ITEM> extends State<TestWidget> {
// -
@override
Widget build(BuildContext context) {
return widget.itemBuilder(0, widget.items[0]);
}
}
Here's how I try to use it:
final items = ["apple", "banana"];
return TestWidget<String>(
items: items,
itemBuilder: (index, item) => Container(color: Colors.green, child: Text(item)),
);
This results in following error:
The following _TypeError was thrown building TestWidget(dirty, state: _TestWidgetState#2d36b): type '(int, String) => Container' is not a subtype of type '(int, dynamic) => Widget'
What am I missing here? I am new to Dart and Flutter.
CodePudding user response:
You are missing the generics on your state, change this line:
class _TestWidgetState<ITEM> extends State<TestWidget> {
to this:
class _TestWidgetState<ITEM> extends State<TestWidget<ITEM>> {