Flutter自动换行和两列布局


Row 和 Column 是 Flex 组件,是无法滚动的,如果没有足够的空间,flutter就提示溢出错误。

这种情况下,Expanded 或 Flexible 组件可用作长文本的自动换行。

在 Flutter文档中 虽然没有明确说明,但是在主轴上如有内容超出空间, Expanded 和 Flexible 会自动换行到纵轴。

1 起源

以下一步步来理解。

如下的场景:

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 组件:

  • 它们所有的子元素都会布局在一个方向
  • 它们不能滚动,所以当内容超出可用范围,flutter就会报错。

2 Expanded组件

接着我们换一种方式,如下,用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')],

),

],

),

原文地址:flutter wrap text instead of overflow

以上是 Flutter自动换行和两列布局 的全部内容, 来源链接: utcz.com/z/321265.html

回到顶部