Flutter入門筆記系列文章部分內(nèi)容來源于《Flutter 實戰(zhàn)》嗤详,如有侵權(quán)請聯(lián)系刪除蜈亩!
Text
Text 用于顯示簡單樣式文本武花,它包含一些控制文本顯示樣式的一些屬性。
為了更加直觀地介紹Text的屬性远舅,直接通過一個例子來說明部分屬性的作用,更多屬性請查閱源碼或官方文檔痕钢。
Text("Hello"), //普通文本
Text(
"Large Hello.", //大號文本
style: TextStyle(
fontSize: 20
),
),
Text(
"WonderfulHello;" * 10, //內(nèi)容重復(fù)十遍
textScaleFactor: 1, //代表文本相對于當(dāng)前字體大小的縮放因子
textAlign: TextAlign.start, //對齊方式
maxLines: 2, //最大行數(shù)
overflow: TextOverflow.ellipsis, //將多余文本截斷后以省略符“...”表示
style: TextStyle( //字體樣式
color: Colors.blue, //字體顏色
fontSize: 24, //字體大小
decoration: TextDecoration.underline, //文字劃線图柏,上劃線、下劃線或刪除線
decorationStyle: TextDecorationStyle.wavy, //劃線樣式
backgroundColor: Colors.black), //組件背景色
)
運行效果如圖
Text
代碼里都有屬性解釋任连,不再贅述蚤吹。
TextSpan
如果我們需要對一個Text內(nèi)容的不同部分按照不同的樣式顯示,這時就可以使用TextSpan随抠,Android中使用SpannableString可以達到類似的效果裁着。
Text.rich(
TextSpan(text: "左邊部分", children: [
TextSpan(
text: "中間部分",
style: TextStyle(
color: Colors.blue,
backgroundColor: Colors.black,
fontSize: 20),
),
TextSpan(
text: "右邊部分",
style: TextStyle(
color: Colors.green,
fontSize: 18,
decoration: TextDecoration.underline,
decorationColor: Colors.black,
),
//recognizer: rec //點擊事件處理器
)
]),
)
我們看到,可以通過Text.rich 方法將TextSpan 添加到Text中來完成字符串的拼接拱她,并且可以自定義不同部分文字的樣式二驰,當(dāng)然也可以通過recognizer定義點擊事件產(chǎn)生的行為。運行效果如下:
TextSpan
DefaultTextStyle
在Widget樹中秉沼,文本的樣式默認是可以被繼承的(子類文本類組件未指定具體樣式時可以使用Widget樹中父級設(shè)置的默認樣式)桶雀,因此,如果在Widget樹的某一個節(jié)點處設(shè)置一個默認的文本樣式唬复,那么該節(jié)點的子樹中所有文本都會默認使用這個樣式矗积,而DefaultTextStyle正是用于設(shè)置默認文本樣式的。
DefaultTextStyle(
style: TextStyle(color: Colors.deepOrange, fontSize: 20),
child: Column(
verticalDirection: VerticalDirection.down,
children: <Widget>[
Text("默認繼承"),
RaisedButton(child: Text("按鈕"), onPressed: null),
Text(
"繼承+自定義",
style: TextStyle(backgroundColor: Colors.grey),
),
//DefaultTextStyle不生效
Text("不繼承+自定義",
style: TextStyle(
//不繼承DefaultTextStyle
inherit: false,
backgroundColor: Colors.grey))
],
))
運行效果如下:
DefaultTextStyle
可以看到敞咧,DefaultTextStyle 設(shè)置給了子樹Column節(jié)點處棘捣,這樣一來Column的所有子孫Text默認都會繼承該樣式,除非Text通過inherit: false
顯示聲明不繼承默認樣式妄均。