ListView.builder() is used to render long or infinite lists, especially lists of data fetched from APIs like products, news, messages, search resultsÂ… Only visible items of the lists are called to reduce resource (CPU, RAM) consumption and improve performance.
Example
1. Create a new Flutter project with the following:Advertisements
flutter create my_product_list
2. Remove all the default code in lib/main.dart and add the following:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key}) : super(key: key);
// Generate a dummy list
final myProducts = List<String>.generate(1000, (i) => 'Product $i');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Product List'),
),
body: Container(
// Use ListView.builder
child: ListView.builder(
// the number of items in the list
itemCount: myProducts.length,
// display each item of the product list
itemBuilder: (context, index) {
return Card(
// In many cases, the key isn't mandatory
key: UniqueKey(),
child: Padding(
padding: const EdgeInsets.all(10),
child: Text(myProducts[index])),
);
}),
));
}
}
3. Run the project:
flutter run
The result:
Conclusion
AdvertisementsWeÂ’ve examined a complete example of implementing a list view in Flutter with the ListView.builder constructor. If youÂ’d like to learn more new and interesting stuff about mobile development, take a look at the following articles:
- How to create a Filter/Search ListView in Flutter
- Working with ReorderableListView in Flutter
- Sorting Lists in Dart and Flutter (5 Examples)
- Flutter SliverList – Tutorial and Example
- Flutter AnimatedList – Tutorial and Examples
You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.