Row 和 Column 是 Flex 组件,是无法滚动的,如果没有足够的空间,flutter就提示溢出错误。
这种情况下,Expanded 或 Flexible 组件可用作长文本的自动换行。
在 Flutter文档中 虽然没有明确说明,但是在主轴上如有内容超出空间, Expanded 和 Flexible 会自动换行到纵轴。
以下一步步来理解。
如下的场景:
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Text overflow', home: Scaffold( appBar: AppBar( title: Text("MyApp"), ), body: Column( children: List.generate(100, (idx) => Text("Short text")) ), ), ); } }
在垂直方向上内容超出纵轴空间,flutter提示如下错误:
I/flutter ( 8390): The following message was thrown during layout: I/flutter ( 8390): A RenderFlex overflowed by 997 pixels on the bottom. I/flutter ( 8390): I/flutter ( 8390): The overflowing RenderFlex has an orientation of Axis.vertical.
横轴呢?
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Text overflow', 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 组件:
接着我们换一种方式,如下,用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')], ), ], ),