返回介绍

Working with long lists

发布于 2019-12-09 21:31:27 字数 2802 浏览 890 评论 0 收藏 0

The standard ListView constructor works well for small lists. In order to work with lists that contain a large number of items, it’s best to use the ListView.builder constructor.

Whereas the default ListView constructor requires us to create all items at once, the ListView.builder constructor will create items as they are scrolled onto the screen.

1. Create a data source

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

For this example, we’ll generate a list of 10000 Strings using the List.generate constructor.

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 as a Widget!

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

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text('${items[index]}'),
    );
  },
);

Complete example

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(
    items: List<String>.generate(10000, (i) => "Item $i"),
  ));
}

class MyApp extends StatelessWidget {
  final List<String> items;

  MyApp({Key key, @required this.items}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final title = 'Long List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text('${items[index]}'),
            );
          },
        ),
      ),
    );
  }
}

Long Lists Demo

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文