列表布局是我们项目开发中最常用的一种布局方式。
ListView
https://book.flutterchina.club/chapter6/listview.htmlListView是最常用的可滚动组件之一,它可以沿一个方向线性排布所有子组件,并且它也支持基于Sliver的延迟构建模型。
我们看看ListView的默认构造函数定义:
ListView({...//可滚动widget公共参数Axis scrollDirection = Axis.vertical, //滚动方向 horizontal 水平;vertical 垂直(默认)bool reverse = false, //组件反向排序ScrollController controller,bool primary,ScrollPhysics physics,EdgeInsetsGeometry padding, //内边距//ListView各个构造函数的共同参数double itemExtent,bool shrinkWrap = false,bool addAutomaticKeepAlives = true,bool addRepaintBoundaries = true,double cacheExtent,List<Widget> children = const <Widget>[],})
上面参数分为两组:第一组是可滚动组件的公共参数,本章第一节中已经介绍过,不再赘述;第二组是ListView各个构造函数(ListView有多个构造函数)的共同参数,我们重点来看看这些参数,:·
itemExtent:该参数如果不为null,则会强制children的“长度”为itemExtent的值;这里的“长度”是指滚动方向上子组件的长度,也就是说如果滚动方向是垂直方向,则itemExtent代表子组件的高度;如果滚动方向为水平方向,则itemExtent就代表子组件的宽度。在ListView中,指定itemExtent比让子组件自己决定自身长度会更高效,这是因为指定itemExtent后,滚动系统可以提前知道列表的长度,而无需每次构建子组件时都去再计算一下,尤其是在滚动位置频繁变化时(滚动系统需要频繁去计算列表高度)。shrinkWrap:该属性表示是否根据子组件的总长度来设置ListView的长度,默认值为false。默认情况下,ListView的会在滚动方向尽可能多的占用空间。当ListView在一个无边界(滚动方向上)的容器中时,shrinkWrap必须为true。addAutomaticKeepAlives:该属性表示是否将列表项(子组件)包裹在AutomaticKeepAlive组件中;典型地,在一个懒加载列表中,如果将列表项包裹在AutomaticKeepAlive中,在该列表项滑出视口时它也不会被GC(垃圾回收),它会使用KeepAliveNotification来保存其状态。如果列表项自己维护其KeepAlive状态,那么此参数必须置为false。addRepaintBoundaries:该属性表示是否将列表项(子组件)包裹在RepaintBoundary组件中。当可滚动组件滚动时,将列表项包裹在RepaintBoundary中可以避免列表项重绘,但是当列表项重绘的开销非常小(如一个颜色块,或者一个较短的文本)时,不添加RepaintBoundary反而会更高效。和addAutomaticKeepAlive一样,如果列表项自己维护其KeepAlive状态,那么此参数必须置为false。注意:上面这些参数并非
ListView特有,在本章后面介绍的其它可滚动组件也可能会拥有这些参数,它们的含义是相同的。
默认构造函数
默认构造函数有一个children参数,它接受一个Widget列表(List)。这种方式适合只有少量的子组件的情况,因为这种方式需要将所有children都提前创建好(这需要做大量工作),而不是等到子widget真正显示的时候再创建,也就是说通过默认构造函数构建的ListView没有应用基于Sliver的懒加载模型。实际上通过此方式创建的ListView和使用SingleChildScrollView+Column的方式没有本质的区别。
ListView(shrinkWrap: true,children: [Text('1'),Text('2'),Text('3'),Text('4'),],),
再次强调,可滚动组件通过一个List来作为其children属性时,只适用于子组件较少的情况,这是一个通用规律,并非
ListView自己的特性,像GridView也是如此。
ListView嵌套示例

ListView(scrollDirection: Axis.horizontal,children: [Container(width: 100, color: Colors.blue),Container(width: 50, color: Colors.red),Text('hello'),Container(width: 100,color: Colors.grey,child: ListView(scrollDirection: Axis.vertical, //默认children: [Container(height: 30, color: Colors.orange),Container(height: 20, color: Colors.yellow),],),),],),
ListView.builder 列表项构造器
ListView.builder适合列表项比较多(或者无限)的情况,因为只有当子组件真正显示的时候才会被创建,也就说通过该构造函数创建的ListView是支持基于Sliver的懒加载模型的。
ListView.builder({...@required IndexedWidgetBuilder itemBuilder,int itemCount,...})
itemBuilder:它是列表项的构建器,类型为IndexedWidgetBuilder,返回值为一个widget。当列表滚动到具体的index位置时,会调用该构建器构建列表项。itemCount:列表项的数量,如果为null,则为无限列表。可滚动组件的构造函数如果需要一个列表项Builder,那么通过该构造函数构建的可滚动组件通常就是支持基于Sliver的懒加载模型的,反之则不支持,这是个一般规律。我们在后面在介绍可滚动组件的构造函数时将不再专门说明其是否支持基于Sliver的懒加载模型了。
示例

ListView.builder(itemCount: 10,itemExtent: 50, //强制ListView子组件高度为 50.0itemBuilder: (BuildContext context, int index) { //context 上下文;index索引return Container(color: Colors.primaries[index % Colors.primaries.length],child: Text('$index'),);},),
ListView.separated 分割器构造器
ListView.separated可以在生成的列表项之间添加一个分割组件,它比ListView.builder多了一个separatorBuilder参数,该参数是一个分割组件生成器。
示例:偶数行添加一条蓝色下划线,奇数行添加一条绿色下划线。

ListView.separated(itemCount: 5,itemBuilder: (context, index) {return Text('$index');},separatorBuilder: (context, index) {return Divider(color: index % 2 == 0 ? Colors.blue : Colors.green);},),
例子:动态列表(处理循环数据)

方法1:使用map方法,再用toList()转换为 List
const listData = [{'name': '张三','brief': '前端开发工程师','avatar':'https://himg.bdimg.com/sys/portraitn/item/d4c8b0c1b7e7b2d0d4c232303132522e',},{'name': '李四','brief': 'UI 设计师','avatar':'https://himg.bdimg.com/sys/portraitn/item/d4c8b0c1b7e7b2d0d4c232303132522e',},];class _MyHomePageState extends State<MyHomePage> {getData() {var temp = listData.map((value) {return ListTile(leading: Image.network(value['avatar']),title: Text(value['name']),subtitle: Text(value['brief']),);});return temp.toList();}@overrideWidget build(BuildContext context) {return ListView(children: this.getData(),);}}
方法2:使用 ListView.builder()
const listData = [{'name': '张三','brief': '前端开发工程师','avatar':'https://himg.bdimg.com/sys/portraitn/item/d4c8b0c1b7e7b2d0d4c232303132522e',},{'name': '李四','brief': 'UI 设计师','avatar':'https://himg.bdimg.com/sys/portraitn/item/d4c8b0c1b7e7b2d0d4c232303132522e',},];class _MyHomePageState extends State<MyHomePage> {@overrideWidget build(BuildContext context) {return ListView.builder(itemCount: listData.length,itemBuilder: (context, index) {var info = listData[index];return ListTile(leading: Image.network(info['avatar']),title: Text(info['name']),subtitle: Text(info['brief']),);},);}}
例子:上拉加载(触底加载下一页)
/lib/loading/InnerLoading.dart
import "package:flutter/material.dart";class InnerLoading extends StatelessWidget {InnerLoading({key, this.width = 24.0, this.padding = 16.0}) : super(key: key);final width;final padding;@overrideWidget build(BuildContext context) {return Container(alignment: Alignment.center,padding: EdgeInsets.all(this.padding),child: SizedBox(width: this.width,height: this.width,child: CircularProgressIndicator(),),);}}
/lib/MyHomePage.dart
import "package:flutter/material.dart";import "package:english_words/english_words.dart";import "./loading/InnerLoading.dart";class MyHomePage extends StatefulWidget {@override_MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {static const loadingTag = '##loading##'; //表尾标记bool isFirstHasPost = false;var _words = <String>[loadingTag];@overrideinitState() {super.initState();_retrieveData();}// _retrieveData 模拟从数据源异步获取数据_retrieveData() {Future.delayed(Duration(seconds: 2)).then((val) {setState(() {// 生成20个单词组成的数组var postWords = generateWordPairs().take(20).map((e) => e.asPascalCase).toList();_words.insertAll(_words.length - 1, postWords);isFirstHasPost = true;});});}@overrideWidget build(BuildContext context) {return ListView.separated(itemCount: _words.length,itemBuilder: (context, index) {var len = _words.length;// 第一次接口返回前,先loading。if (!isFirstHasPost) {return InnerLoading();} else {// 如果未到末尾,加载单词列表项if (_words[index] != loadingTag) {return ListTile(title: Text(_words[index]));} else {// 不足80条,继续获取数据if (len - 1 < 80) {_retrieveData(); // 通过 ListView.separated 创建的ListView是支持基于Sliver的懒加载模型的。return InnerLoading(width: 24.0, padding: 16.0);} else {// 已经加载了80条数据,不再获取数据return Container(alignment: Alignment.center,padding: EdgeInsets.all(16),child: Text('没有更多了'),);}}}},separatorBuilder: (context, index) => Divider(height: 0.0),);}}
例子:添加固定列表头
很多时候我们需要给列表添加一个固定表头,比如我们想实现一个商品列表,需要在列表顶部添加一个“商品列表”标题,期望的效果如图所示:
我们按照之前经验,写出如下代码:
@overrideWidget build(BuildContext context) {return Column(children: <Widget>[ListTile(title:Text("商品列表")),ListView.builder(itemBuilder: (BuildContext context, int index) {return ListTile(title: Text("$index"));}),]);}
然后运行,发现并没有出现我们期望的效果,相反触发了一个异常;
Error caught by rendering library, thrown during performResize()。Vertical viewport was given unbounded height ...
从异常信息中我们可以看到是因为ListView高度边界无法确定引起,所以解决的办法也很明显,我们需要给ListView指定边界,我们通过SizedBox指定一个列表高度看看是否生效:
... //省略无关代码SizedBox(height: 400, //指定列表高度为400child: ListView.builder(itemBuilder: (BuildContext context, int index) {return ListTile(title: Text("$index"));}),),...
运行效果:
可以看到,现在没有触发异常并且列表已经显示出来了,但是我们的手机屏幕高度要大于400,所以底部会有一些空白。那如果我们要实现列表铺满除表头以外的屏幕空间应该怎么做?直观的方法是我们去动态计算,用屏幕高度减去状态栏、导航栏、表头的高度即为剩余屏幕高度,代码如下:
... //省略无关代码SizedBox(//Material设计规范中状态栏、导航栏、ListTile高度分别为24、56、56height: MediaQuery.of(context).size.height-24-56-56,child: ListView.builder(itemBuilder: (BuildContext context, int index) {return ListTile(title: Text("$index"));}),)...
运行效果:
可以看到,我们期望的效果实现了,但是这种方法并不优雅,如果页面布局发生变化,比如表头布局调整导致表头高度改变,那么剩余空间的高度就得重新计算。那么有什么方法可以自动拉伸ListView以填充屏幕剩余空间的方法吗?当然有!答案就是Flex。前面已经介绍过在弹性布局中,可以使用Expanded自动拉伸组件大小,并且我们也说过Column是继承自Flex的,所以我们可以直接使用Column+Expanded来实现,代码如下:
@overrideWidget build(BuildContext context) {return Column(children: <Widget>[ListTile(title:Text("商品列表")),Expanded(child: ListView.builder(itemBuilder: (BuildContext context, int index) {return ListTile(title: Text("$index"));}),),]);}
运行后,和上图一样,完美实现了!
总结
本节主要介绍了ListView的一些公共参数以及常用的构造函数。不同的构造函数对应了不同的列表项生成模型,如果需要自定义列表项生成模型,可以通过ListView.custom来自定义,它需要实现一个SliverChildDelegate用来给ListView生成列表项组件,更多详情请参考API文档。
ListTile
https://flutterchina.club/tutorials/layout/#listtile
将最多3行文字,以及可选的行前和和行尾的图标排成一行。
属性
title标题subtitle副标题leading前缀trailing后缀dense是否紧凑模式visualDensity紧凑。horizontal 水平紧凑; vertical 垂直紧凑;限制范围 [-4, 4]
visualDensity: VisualDensity(horizontal: -4, vertical: -4) 。
contentPadding内边距tileColor背景色selectedTileColor选中状态背景色,需搭配selected: true才能生效。selected: true是否选中- …
示例:
ListView(scrollDirection: Axis.vertical, //horizontal 水平;vertical 垂直children: [ListTile(title: Text('我是一级标题'),subtitle: Text('我是二级标题'),),ListTile(leading: Icon(Icons.search),title: Text('我是一级标题'),subtitle: Text('我是二级标题'),),ListTile(trailing: Icon(Icons.search),title: Text('我是一级标题'),subtitle: Text('我是二级标题'),isThreeLine: true,dense: true, //是否紧凑contentPadding: EdgeInsets.all(0), //内边距tileColor: Colors.blue, //背景色),ListTile(leading: Icon(Icons.search),title: Text('我是一级标题'),subtitle: Text('我是二级标题'),selectedTileColor: Colors.red, //背景色selected: true,),],);

