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(...);
}
}
2
Answers
from what i understand,you trying to create a custom widget from a list view item if so you could do it like below. Note i am using a list of string as items as an example but you can use any Objects. kindly correct me if this is not what you are trying to do:
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:And here
WidgetBuilder
is defined as: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: