Flutter自动换行和两列布局
Row 和 Column 是 Flex 组件,是无法滚动的,如果没有足够的空间,flutter就提示溢出错误。
这种情况下,Expanded 或 Flexible 组件可用作长文本的自动换行。
在 Flutter文档中 虽然没有明确说明,但是在主轴上如有内容超出空间, Expanded 和 Flexible 会自动换行到纵轴。
1起源
以下一步步来理解。
如下的场景:
classMyAppextendsStatelessWidget{
//Thiswidgetistherootofyourapplication.
@override
Widgetbuild(BuildContextcontext){
returnMaterialApp(
title:'Textoverflow',
home:Scaffold(
appBar:AppBar(
title:Text("MyApp"),
),
body:Column(
children:List.generate(100,(idx)=>Text("Shorttext"))
),
),
);
}
}
在垂直方向上内容超出纵轴空间,flutter提示如下错误:
I/flutter(8390):Thefollowingmessagewasthrownduringlayout: I/flutter(8390):ARenderFlexoverflowedby997pixelsonthebottom. I/flutter(8390): I/flutter(8390):TheoverflowingRenderFlexhasanorientationofAxis.vertical.
横轴呢?
classMyAppextendsStatelessWidget{
//Thiswidgetistherootofyourapplication.
@override
Widgetbuild(BuildContextcontext){
returnMaterialApp(
title:'Textoverflow',
home:Scaffold(
appBar:AppBar(title:Text("MyApp"),),
body:Column(
children:<Widget>[
Row(
children:<Widget>[
Text(String.fromCharCodes(List.generate(100,(i)=>65)))
],
),
],
),
),
);
}
}
同样也会报错:
如果我们简单地使用Row组件:Row 和 Column 都是 Flex 组件:
- 它们所有的子元素都会布局在一个方向
- 它们不能滚动,所以当内容超出可用范围,flutter就会报错。
2Expanded组件
接着我们换一种方式,如下,用Row来组织左右2个元素:
Column(
children:<Widget>[
Row(
children:<Widget>[Text('AAAA'),Text('ZZZZ')],
),
],
),
第一个元素再换成 Expanded ,这样剩余的空间就会被第一个元素填充:
Column(
children:<Widget>[
Row(
children:<Widget>[
Expanded(child:Text('AAAA')),
Text('ZZZZ')],
),
],
),
这样,当第一个元素是一个长文本,并且两个元素内容长于可用范围时,第一个元素会自动换行:
Column(
children:<Widget>[
Row(
children:<Widget>[
Expanded(child:Text(String.fromCharCodes(List.generate(100,(i)=>65)))),
Text('ZZZZ')],
),
],
),
原文地址:flutterwraptextinsteadofoverflow