fluttern使用長列表

標準的ListView構造函數適用于小列表。 為了處理包含大量數據的列表,最好使用ListView.builder構造函數。
ListView的構造函數需要一次創(chuàng)建所有項目,但ListView.builder的構造函數不需要,它將在列表項滾動到屏幕上時創(chuàng)建該列表項。

1. 創(chuàng)建一個數據源

首先,我們需要一個數據源來。例如,您的數據源可能是消息列表、搜索結果或商店中的產品。大多數情況下,這些數據將來自互聯網或數據庫。

在這個例子中,我們將使用List.generate構造函數生成擁有10000個字符串的列表

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

2. 將數據源轉換成Widgets

為了顯示我們的字符串列表,我們需要將每個字符串展現為一個Widget !
這正是ListView.builder發(fā)揮作用的地方。在我們的例子中,我們將每一行顯示一個字符串

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

完整的例子

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

void main() {
  runApp(new MyApp(
    items: new 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 new MaterialApp(
      title: title,
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(title),
        ),
        body: new ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return new ListTile(
              title: new Text('${items[index]}'),
            );
          },
        ),
      ),
    );
  }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容