What are the differences between ListView.builder and the map function when creating list of widgets? and when should we use one over the other?.
CodePudding user response:
if you have a long list of items, use ListView.builder()
. it only build items that are visible in the screen. Each time the user scrolls the list it builds the next visible item.
if you use
Column(
children: items.map((items){
return ...
}).toList()
)
it has a heavy build cost.
so, the best practice in my opinion is that use ListView.builder()
.
you could use map
if you are sure the items are not more than a few items.
CodePudding user response:
They are methods with different purposes. You can use map method of a list in order to transform it into a different iterable. ListView.builder on the other hand, is a widget with itemBuilder method. I assume you are asking the difference between ListView() and ListView.builder() constructors.
ListView() constructor takes argument children where you can use map method of your list to create a list of widgets. These widgets are rendered immediately when the build method is called.
ListView.builder() on the other hand, takes itemBuilder and itemCount parameters. The difference is that it doesn't render objects immediately but only when they need to be visible on screen. So if you have a large list, the only items that are supposed to be visible due to scroll are rendered, others are not. When you scroll down, new items will be rendered and previous ones are not rendered anymore. If you have 1000 items but only 10 fits the page, that 10 is rendered. So this way it uses memory efficiently.
Use ListView.builder() whenever you have list of data that needs be transformed to a list of widgets. Only use ListView() when you manually create widgets or if you are using small lists.
Examples for both:
final list = ['this', 'is', 'my', 'list'];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) => Text(list[index]),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: const [
Text('Some Text'),
Text('Some different text'),
Text('Another'),
Text('Some Text'),
],
),
);
}