Flutter学习笔记(三)

1. 内置基础组件(图文)

1.1. Text

Text组件就可以当成是Android里面的TextView,用来显示一段文本

1
2
3
4
5
6
7
8
Container(
child: Text(
'虚荣,是我最喜欢的原罪!',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.bold),
),
)

这里外面加了Container作为Text组件的父容器

textAlign属性用于居中文本,那应当是相当于Text自身,那需要关注一下Text组件自身有没有变化,之前的Align组件和Containeralignment属性都是会使容器变化的

因此加上一个样式属性,查看一下组件的有效区域

1
2
3
4
5
6
7
8
9
10
11
Container(
child: Text(
'虚荣,是我最喜欢的原罪!',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: Colors.lightGreenAccent // 加上一个背景色
),
),
)

并没有变化,依然是"wrap_content"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Container(
color: Colors.lightBlue,
width: 300,
height: 300,
child: Text(
'虚荣,是我最喜欢的原罪!',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: Colors.lightGreenAccent
),
),
)

这里的textAlign可以理解为就是文本组件对于它的容器的一种位置

文本组件恰好包裹文字内容,但是对齐是相对于父级组件也就是Container

TextAlign中有一段注释

1
/// Whether and how to align text horizontally.

这里表述的是该对齐只是水平方向上的,因此上文是水平居中


overflow属性虽然设置,但此刻并未生效,需要改动一下父容器,使文字溢出

由于父容器宽度变小了,空间显得局促,因而在显示不下时,会采用实现设置的方式对文本进行省略


style属性主要借助于TextStyle来实现样式的修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Container(
color: Colors.lightBlue,
width: 100,
height: 300,
child: Text(
'虚荣,是我最喜欢的原罪!',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.deepOrange, // 字体颜色
fontWeight: FontWeight.bold, // 加粗
backgroundColor: Colors.lightGreenAccent, // 背景
letterSpacing: 10 // 字间距
),
),
)

1.2. Image

Image组件主要用来展示图片,既可以是网络图片,也可以是本地资源

1.2.1. 本地图片

使用本地图片资源首先需要进行一些配置

项目的根目录下新建文件夹images,以及子级目录3.0x2.0x,系统会根据设备不同的像素密度自动加载

这里就随便一点了

然后修改配置文件pubspec.yaml

1
2
3
4
5
# To add assets to your application, add an assets section, like this:
assets:
- images/bg.jpg
- images/2.0x/bg.jpg
- images/3.0x/bg.jpg

注意:

YAML格式要对齐

1
2
3
4
Container(
color: Colors.lightBlue,
child: Image.asset('images/bg.jpg'),
)

使用assets构造器加载

1.2.2. 网络图片

使用network构造器实现网络图片加载

1
2
3
4
5
6
7
8
Container(
color: Colors.lightBlue,
width: 300,
height: 300,
child: Image.network(
'https://i0.hdslb.com/bfs/archive/ca375eb31fa90b8e23b88ed3433c2f60de1c2e6e.png',
),
)

组件还是要在具体场景使用中积累,**“每周组件”**的视频和组件API文档才是最有用的


Flutter组件库文档(https://api.flutter.dev/flutter/widgets/widgets-library.html)

每日一组件(https://youtu.be/c1xLMaTUWCY)https://youtu.be/c1xLMaTUWCY)