Flutter 之 ListView
阿新 • • 發佈:2020-11-22
在 Flutter 中,ListView 可以沿一個方向(垂直或水平方向)來排列其所有子 Widget,常被用於需要展示一組連續檢視元素的場景
ListView 構造方法
- ListView:僅適用於列表中含有少量元素的場景
- ListView.build:適用於子 Widget 比較多的場景
- ListView.separated:適用於需要設定分割線的場景
構造方法名 | 特點 | 使用場景 |
---|---|---|
ListView | 一次性建立好所有子 Widget | 適用於展示少量連續子 Widget 的場景 |
ListView.build | 提供了子 Widget 建立方法,僅在需要展示時才建立 | 適用於子 Widget 較多,且視覺效果呈現某種規律性的場景 |
ListView.separated | 提供了子 Widget 建立方法,僅在需要展示時才建立,且提供了自定義分割線的功能 | 適用於子 Widget 較多,且視覺效果呈現某種規律性、每個子 Widget 之間需要分割線的場景 |
ListView
可以通過設定 children 引數,將所有子 Widget 包含到 listView 中,但這種建立方法要求提前將所有子 Widget 一次性建立好,而不是等到真正需要在螢幕上顯示時才建立,即這種方法是導致效能下降。因此,這種方式只適合列表中含有少量元素的場景
class List extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Android小白營"),
),
body: ListView(
children: <Widget>[
ListTile(
leading: Icon(
Icons.home,
color: Colors.cyan, // 圖示顏色
),
title: Text("首頁"),
selected: true, // 設定狀態為選中狀態
),
ListTile(
leading: Icon(
Icons.add_shopping_cart,
color: Colors.black54,
),
title: Text("購物車"),
),
ListTile(
leading: Icon(
Icons.account_circle,
color: Colors.black54,
),
title: Text("我的"),
)
],
),
);
}
}
資源搜尋網站大全 http://www.szhdn.com 廣州VI設計公司https://www.houdianzi.com
ListView.builder
- itemBuilder:列表項的建立方法。當列表滾動到相應位置時,ListView 會呼叫該方法建立對應的子 Widget
- itemCount:列表項的數目。如果不設定或設定為空,則表示 ListView 為無限列表
- itemExtent:列表項高度。可選引數,但對於定高的列表項元素,建議設定該引數的值(不設定時,ListView 會動態的根據子 Widget 建立完成後的結果,決定自身的檢視高度,以及子 Widget 在 ListView 中的相對位置)
class ListBuild extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemBuilder: (context, index) => ListTile(
leading: Icon(Icons.adb),
title: Text("下標" + index.toString()),
),
itemExtent: 46, // 列表項高度
itemCount: 50, //列表項總數,不設定為無限載入
),
);
}
}
ListView.separatorBuilder
設定列表項之間的分隔線,可以根據下標設定不同的分隔線
class ListSeparated extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Android小白營"),
),
body: ListView.separated(
itemBuilder: (context, index) => GestureDetector(
child: ListTile(
leading: Icon(Icons.adb),
title: Text("下標" + index.toString()),
),
onTap: () => Fluttertoast.showToast(msg: index.toString()), // 列表項點選事件
),
separatorBuilder: (BuildContext context, index) {
divider divider;
if (index % 2 == 0) {
divider = Divider(
thickness: 1, // 分隔線寬度
height: 0,
color: Colors.black12, // 分隔線顏色
);
} else {
divider = Divider(
thickness: 2,
height: 0,
color: Colors.deepOrangeAccent,
);
}
return divider;
},
itemCount: 100,
),
);
}
}