Flutter之文本

1.作用

用于显示简单样式文本。用法如下所示:

1
2
3
4
5
Text('hello world', textAlign: TextAlign.center);

Text('hello world'*4, maxLines: 1, overflow: TextOverflow.ellipsis);

Text('hello world', textScaleFactor: 1.5);

2.Text方法的几个参数代表的意思

  • 1.textAlign: 文本的对齐方式,可以选择左对齐,右对齐还是居中;这几个值都是从TextAlign里面获取。需要注意,对齐的参考系是Text Widget本身,这意味着如果Text的宽度和文本内容长度相等的话,那么此时指定对齐方式是没有意义的。

  • 2.maxLines, overflow: 指定文本显示的最大行数,默认情况下,文本是自动折行的。但是如果指定了maxLine的话,那么最多显示maxLines行,超出了maxLines行的行为由overflow的值来决定,默认是直接截断;如果想要显示省略号的话,那么使用TextOverflow.ellipsis值。

  • 3.textScaleFactor: 代表文本相对于当前字体大小(style属性里面的fontSize)的缩放因子。

  • 4.style: 他的值是一个TextStyle类所实例化出来的对象,举个例子如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
Text(
'hello world',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black, // 字体颜色
background: new Paint()..color = Colors.white, // 字体底层的颜色(背景颜色)
fontSize: 20,
fontFamily: 'Courier',
decoration: TextDecoration.underline,
height: 1.3
)
);

需要注意的地方,TextStyle类的实例化参数height是一个因子,具体行高等于fontSize乘height。

3.TextSpan:如果是Text是p元素的话,那么TextSpan就是span元素。

如果想要对Text的不同部分应用不同的效果的话,那么使用TextSpan会更加方便。可以先看看TextSpan的构造函数:

1
2
3
4
5
6
7
// 采用了命名可选参数的写法,采用这种写法的话,除非带上@required的话否则都是可选
const TextSpan({
TextStyle style,
String text,
List<TextSpan> children,
GestureRecognizer recognizer
});

各个参数的解释:

  • 1.children,一个TextSpan数组,说明TextSpan里面可以包含其它TextSpan
  • 2.recognizer,在文本片段上进行手势处理

举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Text.rich(TextSpan(
children: [
TextSpan(
text: '主页:'
),
TextSpan(
text: 'hotfireeagle.github.io',
style: TextStyle(
color: Colors.blue
),
recognizer: gotoLink, // 手势处理方法
)
]
))

4.DefaultTextStyle

在Widget树中,文本的样式默认是可以继承的。因此,如果在Widget树中的某个节点处设置一个默认的文本样式的话,那么该节点下的子树中的所有文本都会默认使用这个样式。不同于web编程,设置默认文本样式可以在任意一个父元素里面,但是在flutter里面如果想要设置默认文本样式的话,那么应该使用DefaultTextStyle这个widget才行。如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DefaultTextStyle(
style: TextStyle(
color: Colors.red,
fontSize: 18.0
),
textAlign: TextAlign.center,
// 注意在这里是child
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
// 注意在这里是children
children: <Widget>[
Text('hello world'),
Text('hello flutter'),
Text('cool', style: TextStyle(color: Colors.green))
]
)
)