Flutter中ListTile列表块的使用详解
在Flutter开发中,ListTile是最常用的组件之一,接下来我们就来看下它的属性以及使用方法。
属性列表
const ListTile({
Key key,
this.leading, //title之前的widget
this.title, //列表块的主要内容
this.subtitle, //title下方显示的内容
this.trailing, //标题后显示的widget,通常是一个[Icon]widget
this.isThreeLine = false, //是否打算显示三行文本
this.dense, //此列表图块是否是垂直密集列表的一部分,如果是true文本将会更小
this.visualDensity,
this.shape,
this.contentPadding, //内容与边框之间的边距,默认是16
this.enabled = true, //列表块是否可交互
this.onTap, //当用户点击此列表图块时调用
this.onLongPress, //当用户长按此列表图块时调用
this.mouseCursor,
this.selected = false, //如果选中列表块,文本和图标的颜色将成为主题的主颜色
this.focusColor,
this.hoverColor,
this.focusNode,
this.autofocus = false,
})
在上面源码中,我们针对ListTile的主要常用属性已经标注了注释,感兴趣的可以针对每个属性,一个一个调试一下。
实例
实例一:ListTile列表
接下来使用实例进行代码实战:
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return new ListTile(
leading: new Icon(Icons.phone),
title: new Text("卜大爷 $index"),
subtitle: new Text("010-12345678"),
trailing: new Icon(Icons.arrow_forward_ios),
contentPadding: EdgeInsets.symmetric(horizontal: 20.0),
enabled: true,
onTap: () => print("$index被点击了"),
onLongPress: () => print("$index被长按了"),
);
},
),
);
}
}
效果图:
实例二:卡片形式的列表
只需要在ListTile外面添加一层Card组件即可:
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return new Card(
child: new ListTile(
leading: new Icon(Icons.phone),
title: new Text("卜大爷 $index"),
subtitle: new Text("010-12345678"),
trailing: new Icon(Icons.arrow_forward_ios),
contentPadding: EdgeInsets.symmetric(horizontal: 20.0),
enabled: true,
onTap: () => print("$index被点击了"),
onLongPress: () => print("$index被长按了"),
));
},
),
);
}
}
效果图: