今天學(xué)習(xí)Flutter的Text組件時(shí)剥悟,遇到了一個(gè)問(wèn)題:Text的overflow: TextOverflow.ellipsis
屬性不生效
目前界面如下:
我想要星標(biāo)后面的文字在很長(zhǎng)的時(shí)候咏尝,顯示為省略號(hào)憾股,于是給Text設(shè)置了overflow: TextOverflow.ellipsis
:
class _LayoutPageState extends State<LayoutPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("LayoutPage")),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.star,
size: 16.0,
color: Colors.grey,
),
Padding(padding: new EdgeInsets.only(left: 5.0)),
Text(
"100010001000100010001000100010001000100010001000100010001000100010001000100010001000100010001000",
style: new TextStyle(color: Colors.grey, fontSize: 14.0),
overflow: TextOverflow.ellipsis,
maxLines: 1,
)
],
),
),
);
}
}
結(jié)果卻提示Text的布局邊界溢出了
最開(kāi)始,我在Text的外面包了個(gè)Expended
class _LayoutPageState extends State<LayoutPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("LayoutPage")),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.star,
size: 16.0,
color: Colors.grey,
),
Padding(padding: new EdgeInsets.only(left: 5.0)),
Expanded(
child: Text(
"100010001000100010001000100010001000100010001000100010001000100010001000100010001000100010001000",
style: new TextStyle(color: Colors.grey, fontSize: 14.0),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
)
],
),
),
);
}
}
顯示結(jié)果是正常的
但是算柳,當(dāng)Text的文本很短時(shí)蕉堰,我希望圖標(biāo)和文字居中,現(xiàn)在卻是在最左邊
所以Expanded的方案失敗赏胚。通過(guò)這,我們也能看出:
凡是添加了Expanded的組件商虐,都會(huì)被撐大到全屏觉阅,從而導(dǎo)致Row的主軸居中失效。
后來(lái)在朋友的提示下秘车,我用Container設(shè)置指定寬度的方式典勇,實(shí)現(xiàn)了這個(gè)需求:
class _LayoutPageState extends State<LayoutPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("LayoutPage")),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.star,
size: 16.0,
color: Colors.grey,
),
Padding(padding: new EdgeInsets.only(left: 5.0)),
Container(
width: 60,
child: Text(
"1000",
style: new TextStyle(color: Colors.grey, fontSize: 14.0),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
)
],
),
),
);
}
}
短文本顯示:
長(zhǎng)文本顯示:
雖然不是完全符合我的需求(屏幕寬度還有,但是卻省略文字了)叮趴,但是也在一定程度上滿足了割笙。
記錄本次解決問(wèn)題的流程,主要是想提醒自己一定要熟悉Flutter的各種布局組件眯亦,以及它的限制伤溉,不能想當(dāng)然般码。
Text組件本身是沒(méi)有寬度的,設(shè)置overflow屬性的話谈火,必須給它指定寬度侈询,可以通過(guò)Expanded設(shè)置為鋪滿,也可以通過(guò)Container設(shè)置為指定寬度糯耍。