7.4 C
New York
Monday, November 27, 2023

Flutter ListView.builder() example

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.


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);

  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');

  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:


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:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.


Related Articles

Latest Articles