1、Flutter 列表组件
Flutter 中我们可以通过 ListView 来定义 列表项,支持垂直和水平方向展示。通过一个属性就可以控制列表的显示方向。列表有一下 分类:
- 1、垂直列表
- 2、垂直图文列表
- 3、水平列表
- 4、动态列表
- 5、矩阵式列表
1.1、列表参数
名称 | 类型 | 说明 |
---|---|---|
scrollDirection | Axis | Axis.horizontal 水平列表 Axis.vertical 垂直列表 |
padding | EdgeInsetsGeometry | 内边距 |
resolve | bool | 组件反向排序 |
children | List | 列表元素 |
1.2、代码示例
import 'package:flutter/material.dart';
// 垂直列表
class MyListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Center(
child: ListView(
// 内边距
// padding: EdgeInsets.all(10),
//方向排序,从底部开始,与正常的相反
reverse: true,
children: <Widget>[
ListTile(
leading: Icon(Icons.phone),
title: Text(
"This is list1",
style: TextStyle(fontSize: 20),
),
subtitle: Text("This is subtitle"),
),
ListTile(
leading: Icon(Icons.phone),
title: Text(
"This is list2",
style: TextStyle(fontSize: 20),
),
subtitle: Text("This is subtitle"),
),
ListTile(
leading: Icon(Icons.phone),
title: Text(
"This is list3",
style: TextStyle(fontSize: 20),
),
subtitle: Text("This is subtitle"),
),
ListTile(
leading: Icon(Icons.phone),
title: Text(
"This is list4",
style: TextStyle(fontSize: 20),
),
subtitle: Text("This is subtitle"),
),
],
),
);
}
}
// 水平列表
class MyListView2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 200,
margin: EdgeInsets.all(2),
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
// 一个纯色的块
Container(
width: 180.0,
color: Colors.lightBlue,
),
// 加载上去一张照片
Container(
width: 180,
color: Colors.amber,
child: ListView(
children: <Widget>[
Image.network(
'https://resources.ninghao.org/images/childhood-in-a-picture.jpg'),
SizedBox(height: 16.0),
Text(
'这是一个文本信息',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16.0),
),
],
),
),
// 屏幕只显示了2个块,之后的可以滑动出来
Container(
width:180.0,
color: Colors.deepOrange, ),
Container(
width:180.0,
color: Colors.deepPurpleAccent,
),
],
),
);
}
}
// 加载动态数据
class MyListView3 extends StatelessWidget {
List list = new List();
MyListView3() {
for (var i = 0; i < 20; i++) {
list.add("这是第${i}条数据");
}
print(list);
}
@override
Widget build(BuildContext context) {
return ListView.builder(
// 指定列数
itemCount: this.list.length,
// 指定内容
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.access_time),
title: Text("${list[index]}"),
);
},
);
}
}
在页面中组件的使用
//指定导入自定义组件
import 'package:flutter_app/MyListView.dart';
void main() => runApp(MyMaterialApp());
class MyMaterialApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "test",
home: new Scaffold(
// 设置title
appBar: AppBar(title: Text("ListViewDemo")),
// 使用组件
body: MyListView3(),
));
}
}