介绍 Text,很常用的一个Widget,作为一个Android 开发者,我把它当成一个TextView来对待。
类结构
构造方法
两个构造方法
可以看到,两个构造方法的不同在于构造方法中的第一个参数,普通的是一个String对象,data; 复杂的是一个TextSpan对象,textSpan。从事Android开发的朋友一定用过SpannableString,感觉上应该会和TextSpan差不多吧。
属性值 style
TextStyle,用来定义Text中文字的各种属性。后面的例子会陆续使用到一些,常用的属性值也是相当好理解的。具体如下:
编写第一个widget Text
return Container(
padding: EdgeInsets.all(15.0),
height: 200,
color: Colors.black12,
child: new Text(
"用来定义Text中文字的各种属性用来定义Text中文字的各种属性",
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis, //省略号
maxLines: 2,
softWrap: false,
style: new TextStyle(
color: Colors.black,
fontSize: 30.0,
),
),
);
textAlign :TextAlign.justify(两端对齐)
textDirection 文本方向
textDirection:TextDirection.ltr textDirection: TextDirection.rtl,
softWrap 是否自动换行,若为false,文字将不考虑容器大小,单行显示,超出屏幕部分将默认截断处理
overflow 当文字超出屏幕的时候,如何处理
TextOverflow.clip(裁剪) / TextOverflow.fade(渐隐) / TextOverflow.ellipsis(省略号)
textScaleFactor 字体显示倍率,上面的例子使用的字体大小是40.0,将字体设置成20.0,然后倍率为2,依然可以实现相同的效果
data & textSpan
data,普通的String类型,无需赘述
textSpan,TextSpan类型,个人觉得TextSpan最大的用处在于处理多种类型和显示效果的文字,以及各自点击事件的处理
return RichText(
text: TextSpan(
text: "今晚打老虎",
style: TextStyle(
fontSize: 40.0,
color: Colors.deepPurpleAccent,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w200),
children: [
new TextSpan(
text: "哈哈哈",
style: TextStyle(
color: Colors.amberAccent,
decoration: TextDecoration.underline,
// decorationColor: Colors.purple,
decorationColor: const Color(0xff000000),
decorationStyle: TextDecorationStyle.solid,
),
recognizer: new TapGestureRecognizer()
..onTap = () =>
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("one is tapped"),
)),
),
new TextSpan(
text: "啊啊啊",
style: new TextStyle(
fontSize: 40.0,
color: Colors.black,
decoration: TextDecoration.lineThrough,
decorationColor: Colors.redAccent,
decorationStyle: TextDecorationStyle.dashed,
), recognizer: new LongPressGestureRecognizer()
..onLongPress = () =>
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("THREE is longpressed"),
)),
)
]
)
);
decoration: TextDecoration.lineThrough, 折扣线
decorationColor: const Color(0xff000000),
decoration: TextDecoration.underline, 下划线
decorationStyle: TextDecorationStyle.dashed, 虚线
fontStyle: FontStyle.italic, 24号字体
fontWeight: FontWeight.bold, 字体加粗