一、RichText和TextSpan的介绍
RichText:如果想在一句话或者一段文字里面显示不同样式的文字,可以使用RichText
TextSpan:用于指定文本片段的风格及手势交互
二、RichText和TextSpan的源码
2.1、RichText的源码
RichText({
Key key,
@required this.text,//显示文本的组件
this.textAlign = TextAlign.start,//对齐方式
this.textDirection,//文本的方向
this.softWrap = true,//文本是否应该在软换行处换行
this.overflow = TextOverflow.clip,//溢出处理方式
this.textScaleFactor = 1.0,//每个逻辑像素的字体像素数
this.maxLines,//最大行数
this.locale,
this.strutStyle,//strut样式
this.textWidthBasis = TextWidthBasis.parent,//文本的宽度
this.textHeightBehavior,
}) : assert(text != null),
assert(textAlign != null),
assert(softWrap != null),
assert(overflow != null),
assert(textScaleFactor != null),
assert(maxLines == null || maxLines > 0),
assert(textWidthBasis != null),
super(key: key, children: _extractChildren(text));
2.2、TextSpan的源码
const TextSpan({
this.text,//String类型的文本
this.children,//子组件
TextStyle? style,//文本的样式
this.recognizer,
this.semanticsLabel,//语义
}) : super(style: style);
三、RichText和TextSpan的属性简介
3.1、RichText的属性
属性 | 说明 |
---|---|
text | 显示文本的组件,一般放TextSpan组件 |
textAlign | 文本对齐方式 TextAlign.left TextAlign.right TextAlign.cente TextAlign.justify TextAlign.start TextAlign.end |
textDirection | 文本的方向 TextDirection.ltr TextDirection.rtl |
overflow | 文字溢出的处理方式 TextOverflow.clip:剪切溢出的文本填满容器。 TextOverflow.fade:将溢出的文本淡化为透明。 TextOverflow.ellipsis:使用省略号表示文本已溢出。 TextOverflow.visible:呈现容器外溢出的文本 |
textScaleFactor | 每个逻辑像素的字体像素数 |
maxLines | 最大行数 |
textWidthBasis | 文本的宽度 |
softWrap | 文本是否应该在软换行处换行 |
3.1、TextSpan的属性
属性 | 说明 |
---|---|
text | String类型的文本 |
children | 子组件 |
style | TextStyle类型的文本样式可以设置文字的大小、颜色、样式等 |
recognizer | 指定手势交互 recognizer: TapGestureRecognizer()..onTap = () {},可以监听点击事件 |
semanticsLabel | 语义 |
四、Demo
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("RichText学习"),
),
body: Container(
padding: EdgeInsets.all(10),
child: RichText(
textScaleFactor: 5,
overflow: TextOverflow.fade,
textDirection: TextDirection.ltr,
textAlign: TextAlign.left,
text: TextSpan(
children: [
TextSpan(
text:
"《上阳赋》自然引来众多关注。章子怡早年凭借出演张艺谋的电影《我的父亲母亲》走红",
style: TextStyle(
color: Colors.black,
),
recognizer: TapGestureRecognizer()..onTap = () {}),
TextSpan(
text: "安全协议",
style: TextStyle(
color: Colors.red,
),
//点击事件
recognizer: TapGestureRecognizer()..onTap = () {
print("点击了安全协议");
})
],
)),
)),
);
085aee68fac02545f778d60fa977e93.png