Flutter 中 ListView 的 4 种构建方式详解 _ Flutter Widgets
warning:
这篇文章距离上次修改已过182天,其中的内容可能已经有所变动。
在Flutter中,ListView是一个非常常用的widget,它可以用来展示一个垂直或者水平滚动的列表。下面是ListView的四种构建方式:
- 默认构造函数:这是最基本的构造函数,用于创建一个包含指定子widget的ListView。
ListView(
children: <Widget>[
ListTile(
title: Text('Item 1'),
),
ListTile(
title: Text('Item 2'),
),
// ...
],
);
- 使用ListView.builder构造函数:当列表项非常多时,使用这个构造函数可以提高效率。因为它是"懒加载"的,只有当需要时才会创建widget。
ListView.builder(
itemCount: 1000,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
);
- 使用ListView.separated构造函数:这个构造函数可以在每个子widget之间添加分隔线。
ListView.separated(
itemCount: 1000,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
separatorBuilder: (context, index) {
return Divider(
color: Colors.black,
);
},
);
- 使用ListView.custom构造函数:这个构造函数提供了更多的自定义选项,比如可以指定滚动方向和滑动行为。
ListView.custom(
scrollDirection: Axis.horizontal,
children: <Widget>[
Container(
width: 100.0,
color: Colors.red,
),
Container(
width: 100.0,
color: Colors.blue,
),
// ...
],
);
以上就是Flutter中ListView的四种构建方式,每种方式都有其适用的场景,开发者可以根据具体需求选择合适的构建方式。
评论已关闭