![]() |
VOOZH | about |
ListView is an important widget in Flutter. It is used to create the list of children. But when we want to create a list recursively without writing code again and again, then ListView.builder is used instead of ListView. ListView.builder creates a scrollable, linear array of widgets.
ListView.builder by default does not support child reordering.
ListView ListView.builder({
Key? key,
Axis scrollDirection = Axis.vertical,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? itemExtent,
double? Function(int, SliverLayoutDimensions)? itemExtentBuilder,
Widget? prototypeItem,
required Widget? Function(BuildContext, int) itemBuilder,
int? Function(Key)? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
HitTestBehavior hitTestBehavior = HitTestBehavior.opaque,
})
Let us understand this concept with the help of an example :
Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.
flutter create app_nameTo know more about it refer this article: Creating a Simple Application in Flutter.
Write the below code in main.dart.
In the above code, we have a ListView.builder class, which is a stateless class. It returns a new Scaffold which consists of an appBar and a body.
In the body, we have ListView.builder with an itemcount of 5 and an itemBuilder that will create a new widget again and again up to 5 times because we have an itemCount=5. If we don't use itemCount in ListView.builder, then we will get infinite list items, so it is recommended to use itemCount to avoid such mistakes. The itemBuilder returns ListTile, which has leading, trailing and title. This ListTile will be built again and again up to 5 times.
The answer to this question is that we can do the same task with the help of ListView but when we have numerous items(for ex: 10000) then it is inefficient to create these items with ListView because it loads all the list items at once but ListView.builder make this task quicker by creating layouts for items visible on the screen with the help of itemBuilder & lazilybuild other layouts/containers as the user scrolls.
Now, from the above code of the ListView.builder, if we want to create a total of 8 items, then simply change itemCount to 8, and we will get 8 items on our screen.