I want to create a custom itemBuilder for a widget that I am creating as it needs to have dynamic widgets for each use case.
How can I implement something like ListView.builder(itemBuilder: ...)
's item builder for my widget?
I tried creating a function as a parameter to get it to work but I was stuck after getting the function, I didn't know how to iterate through it.
class ViewClass extends StatelessWidget{
ViewClass({
this.key,
required this.itemBuilder,
});
final Function(Widget item) itemBuilder;
@override
Widget build(BuildContext context) {
return Container(...);
}
}
Flutter is open source, you could just try to look into ListView.builder
's source code (by control clicking it from your IDE) to look how it's done, but there's an even much simpler widget: Builder
. It's probably the simplest widget that has such a feature. So simply look how they do it. And that's:
class Builder extends StatelessWidget {
/// Creates a widget that delegates its build to a callback.
const Builder({
super.key,
required this.builder,
});
/// Called to obtain the child widget.
///
/// This function is called whenever this widget is included in its parent's
/// build and the old widget (if any) that it synchronizes with has a distinct
/// object identity. Typically the parent's build method will construct
/// a new tree of widgets and so a new Builder child will not be [identical]
/// to the corresponding old one.
final WidgetBuilder builder;
@override
Widget build(BuildContext context) => builder(context);
}
And here WidgetBuilder
is defined as:
typedef WidgetBuilder = Widget Function(BuildContext context);
So what you did wrong is actually you defined itemBuilder
as a Function that takes a widget as argument, but you needed one that returns it. So you could do this for example:
class ViewClass extends StatelessWidget{
const ViewClass({
super.key,
required this.itemBuilder,
});
final Widget Function() itemBuilder;
@override
Widget build(BuildContext context) {
return Container(child: itemBuilder());
}
}