The standard ListViewconstructor works well for small lists. In order to work with lists that containa large number of items, it’s best to use theListView.builderconstructor.

Whereas the default ListView constructor requires us to create all items atonce, the ListView.builder constructor will create items as they are scrolledonto the screen.

1. Create a data source

First, we’ll need a data source to work with. For example, your data sourcemight be a list of messages, search results, or products in a store. Most ofthe time, this data will come from the internet or a database.

For this example, we’ll generate a list of 10000 Strings using theList.generateconstructor.

  1. final items = List<String>.generate(10000, (i) => "Item $i");

2. Convert the data source into Widgets

In order to display our List of Strings, we’ll need to render each String asa Widget!

This is where the ListView.builder will come into play. In our case, we’lldisplay each String on its own line.

  1. ListView.builder(
  2. itemCount: items.length,
  3. itemBuilder: (context, index) {
  4. return ListTile(
  5. title: Text('${items[index]}'),
  6. );
  7. },
  8. );

Complete example

  1. import 'package:flutter/foundation.dart';
  2. import 'package:flutter/material.dart';
  3. void main() {
  4. runApp(MyApp(
  5. items: List<String>.generate(10000, (i) => "Item $i"),
  6. ));
  7. }
  8. class MyApp extends StatelessWidget {
  9. final List<String> items;
  10. MyApp({Key key, @required this.items}) : super(key: key);
  11. @override
  12. Widget build(BuildContext context) {
  13. final title = 'Long List';
  14. return MaterialApp(
  15. title: title,
  16. home: Scaffold(
  17. appBar: AppBar(
  18. title: Text(title),
  19. ),
  20. body: ListView.builder(
  21. itemCount: items.length,
  22. itemBuilder: (context, index) {
  23. return ListTile(
  24. title: Text('${items[index]}'),
  25. );
  26. },
  27. ),
  28. ),
  29. );
  30. }
  31. }

Long Lists Demo