目錄
回顧
上一篇0901博客裏介紹了導航欄,要基於MaterialApp和Scaffold,並且在Scaffold父容器裏添加了導航欄,接下來,還是基於Scaffold容器,添加body屬性
Text常用屬性
style: TextStyle(
height: 10,
fontSize: 30,
color: Colors.green,
backgroundColor: Colors.yellow,
letterSpacing: 5.0,
fontWeight: FontWeight.w900,
decoration: TextDecoration.lineThrough,
decorationStyle: TextDecorationStyle.dashed,
decorationColor: Colors.purple
)TextStyle屬性設置控件
高度
字號
字體顏色
背景顏色
字符間距
加粗
設置下劃線(文字上方,中間,下方)
下劃線格式(直線,虛線(橫線虛線,雙橫線虛線,單橫線虛線,點點虛線))
下劃線顏色
backgroundColor: Colors.green, background: new Paint()..color=Colors.yellow
這兩種設置背景,不能同時出現,會報錯,建議用後者
maxLines:1, 最大行數 textScaleFactor: 1.7 文字縮放倍數 overflow: TextOverflow.ellipsis, 如果文字過多,末尾用省略號代替或者截斷文本 softWrap: false, 設置是否是單行顯示 textAlign: TextAlign.left, 文本的對齊方式 '我是文本控件'*10 *10複製10次 fontFamily: "Courier" 設置字體樣式 inherit: false, false不繼承默認樣式,通常和DefaultTextStyle一起使用
測試
void main() { runApp(MyAppText()); } class MyAppText extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( backgroundColor: Colors.red, title: Text('Text文本控件練習'), textTheme: TextTheme( title: TextStyle( fontSize: 18, color: Colors.yellow ) ), ), body: TextClass(), ), ); } } class TextClass extends StatelessWidget{ @override Widget build(BuildContext context) { // TODO: implement build return Text( 'Hello world哈哈哈' * 10, style: TextStyle( fontSize: 30, color: Colors.blue, height: 1.2, decoration: TextDecoration.underline, decorationColor: Colors.purple, decorationStyle: TextDecorationStyle.dashed, fontFamily: 'Courier', background: new Paint()..color=Colors.yellow, letterSpacing: 5, fontWeight: FontWeight.w600 ), textAlign: TextAlign.center, textScaleFactor: 1.1, ); } }
運行效果
TextSpan屬性
要對一個Text內容的不同部分按照不同的樣式顯示,這時就可以使用
TextSpan
,它代表文本的一個“片段”這裏要用到Text.rich
class TextClass extends StatelessWidget{ @override Widget build(BuildContext context) { // TODO: implement build return Text.rich( TextSpan( style: TextStyle( fontSize: 30, color: Colors.blue ), children: [ TextSpan(text: 'hello '), TextSpan(text: 'world '), TextSpan( text: '哈哈哈 ', style: TextStyle( fontSize: 14, color: Colors.purple ) ) ] ) ); }
DefaultTextStyle
文本的樣式默認是可以被繼承的(子類文本類組件未指定具體樣式時可以使用Widget樹中父級設置的默認樣式),因此,如果在Widget樹的某一個節點處設置一個默認的文本樣式,那麼該節點的子樹中所有文本都會默認使用這個樣式,而
DefaultTextStyle
正是用於設置默認文本樣式的class TextClass extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return DefaultTextStyle( style: TextStyle(fontSize: 30, color: Colors.red), child: Column( children: <Widget>[ Text('hello world'), Text('哈哈哈') ], ), ); }
如果在Text裏調用inherit: false,我們看下效果
Text('哈哈哈', style: TextStyle( inherit: false, color: Colors.green ), )