In Flutter, 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:
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',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key}) : super(key: key);
// Generate a massive list of dummy products
final myProducts = List<String>.generate(1000, (i) => 'Product $i');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('KindaCode.com'),
),
// implement the list view
body: 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: ValueKey(myProducts[index]),
margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 15),
child: Padding(
padding: const EdgeInsets.all(10),
child: Text(myProducts[index])),
);
}));
}
}
3. Run the project:
flutter run
The result:
Conclusion
We’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
- Flutter & Dart: Count Occurrences of each Element in a List
- 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.