Flutter ListView.builder() example

Last updated on October 14, 2021 A Goodman Loading... Post a comment

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',
      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

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:

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles