Flutter Text组件详解
Flutter中用于显示文字的组件是Text。
Flutter中用于显示文字的组件是Text,本文介绍Text相关的内容:
Text及其基本属性
1、TextStyle
2、TextSpan
3、DefaultTextStyle
一、Text属性说明
属性 | 说明 |
---|
style | 文字样式(颜色、粗细) |
textAlign | 文字对齐样式 |
overflow | 文字字数超出后样式 |
textScaleFactor | 文字大小 |
maxLines | 最大行数 |
代码示例:
textScaleFactor:设置文字大小的属性
textAlign:文字的对齐方式,为确保此属性有效,请确保文字内容长度足够
maxLines:文本显示的最大行数
overflow:文本超过一行的处理方式(TextOverflow.ellipsis多出部分用省略号代替...
Text("Hello World"),//默认没有使用样式
Text("Hello World",textScaleFactor: 2.0,),//默认没有使用样式
Text("Hello World"*6,textAlign: TextAlign.right),
Text("Hello World"*6,textAlign: TextAlign.right,maxLines: 1,),
Text("Hello World"*6,textAlign: TextAlign.right,overflow: TextOverflow.ellipsis,),
运行效果:

二、TextStyle
TextStyle是Text的其中一个属性,因为它的内容较多单独说明
TextStyle用于指定文本显示的样式如颜色、字体、粗细、背景等
属性 | 说明 |
---|
color | 颜色 |
backgroundColor | 背景色 |
fontSize | 字体大小 |
fontWeight | 字体权重(粗细) |
fontStyle | 样式 |
letterSpacing | 字符间隔 |
wordSpacing | 单词间隔 |
decoration | 文本装饰 |
decorationStyle | 文本装饰样式 |
示例
Text("Hello World",style:
TextStyle(color: Colors.red,backgroundColor:Color(0x88888888),
fontSize: 20,fontWeight:FontWeight.bold,
fontStyle:FontStyle.italic,
letterSpacing:5,wordSpacing: 50, decoration:TextDecoration.underline,decorationStyle:TextDecorationStyle.solid)
,),
三、TextSpan
TextSpan用于对同一段Text内容的不同片段进行不同的设置(样式、处理)
Text.rich(TextSpan(text: "Please Select Item:",
children: [
TextSpan(text: "红:",style: TextStyle(color: Colors.red),
recognizer: new TapGestureRecognizer()..onTap=(){Fluttertoast.showToast(msg: "你选择了红");}),
TextSpan(text: "蓝",style: TextStyle(color: Colors.blue),
recognizer:new TapGestureRecognizer()..onTap=(){Fluttertoast.showToast(msg: "你选择了蓝",);})
]))
四、DefaultTextStyle
在Widget树中,文本的样式默认是可以被继承的
如果在Widget树的某一个节点处设置一个默认的文本样式,那么该节点的子树中所有文本都会默认使用这个样式
DefaultTextStyle(style: TextStyle(
color:Colors.red,
fontSize: 20.0,
), child: Column(
children: [
Text("Hello World 1"),
Text("Hello World 2"),
Text("Hello World 3",style: TextStyle(
inherit:false, //不继承默认样式
color: Colors.blue,fontSize: 30.0
),),
],
))
说明:
Text 1和Text 2继承默认样式
Text3中设置inherit不继承样式,并自己实现了TextStyle