Flutter学习笔记(四)

1. 列表组件

在实际的应用中,经常会有需要向用户提供大量数据进行阅读的场景,这就需要使用到列表组件展示数据

1.1. ListView

1
2
3
4
5
6
7
8
9
ListView(
children: [
Text('内容'),
ElevatedButton(
onPressed: () => {},
child: Text('按钮')
)
],
)

对于ListView组件而言最重要的是内容,也就是children属性,它所接收的是Widget列表,理论上只要是Widget就可以放

image-20220408234337755

通常是使用ListTile组件进行搭配使用

ListTile代表的就是列表中的一项,利用其属性可以方便组合列表项的样式

1
2
3
4
5
6
ListTile(
leading: Image.network('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ffile01.dysucai.com%2Fd%2Ffile%2Flan2018061913%2Fk0ajx12543d.jpg&refer=http%3A%2F%2Ffile01.dysucai.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651720679&t=7c87729681050f86d1340f1412b7eb52'), // 开头的图片
title: Text('标题'), // 标题
subtitle: Text('二级标题'), // 子标题
trailing: Icon(Icons.keyboard_arrow_right), // 结尾的图片
),

以上就是ListTile常用的一些属性,然后多复制几个

ListView默认是沿垂直方向滚动,可以通过scrollDirection属性进行修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
width: 150,
color: Colors.blueAccent,
),
Container(
width: 150,
color: Colors.yellowAccent,
),
Container(
width: 150,
color: Colors.orangeAccent,
)
],
)
image-20220409145802224

注意:

设置沿水平方向滚动,高度会自适应父容器;设置垂直方向滚动,宽度会自适应父容器

也可以为列表项设置子组件为ListView,实现嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
ListView(
scrollDirection: Axis.horizontal,
children: [
Container(
width: 150,
color: Colors.blueAccent,
),
Container(
width: 150,
color: Colors.yellowAccent,
child: ListView( // 子组件依然是列表
children: [
Container(
height: 250,
color: Colors.black,
),
Container(
height: 250,
color: Colors.white,
),
Container(
height: 250,
color: Colors.red,
)
],
),
),
Container(
width: 150,
color: Colors.orangeAccent,
)
],
)
image-20220409150334357

1.2. GridView

用于以网格的形式呈现数据的组件,因为默认是沿垂直方向滚动的,因此垂直方向为主轴,水平方向便是副轴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
GridView.count(
crossAxisCount: 2, // 列数,副轴
children: [
Container(
color: Colors.deepOrange,
),
Container(
color: Colors.lightBlue,
),
Container(
color: Colors.blueGrey,
),
Container(
color: Colors.amber,
)
],
)
image-20220409162101304
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GridView.count(
crossAxisCount: 2, // 列数,副轴
mainAxisSpacing: 10, // 沿主轴的间隙
crossAxisSpacing: 20, // 沿副轴的间隙
children: [
Container(
color: Colors.deepOrange,
),
Container(
color: Colors.lightBlue,
),
Container(
color: Colors.blueGrey,
),
Container(
color: Colors.amber,
)
],
)
image-20220409162313898

GridView中的每一项都是进行自适应的,需要修改item的比例需要通过childAspectRatio设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
GridView.count(
crossAxisCount: 2, // 列数,副轴
mainAxisSpacing: 10, // 沿主轴的间隙
crossAxisSpacing: 20, // 沿副轴的间隙
childAspectRatio: 0.8, // 子项宽高比
children: [
Container(
color: Colors.deepOrange,
),
Container(
color: Colors.lightBlue,
),
Container(
color: Colors.blueGrey,
),
Container(
color: Colors.amber,
)
],
)
image-20220409162840338