Flutter自动换行和两列布局

25.4k 记录 2评论

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

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

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

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 组件:RowColumn 都是 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

2 条评论

K
Kylin says: 回复

很开心,解决了我的溢出问题,我也看到原文了,但是原文图片看不见哈哈哈。

小河马 says: 回复

怎么让你最后这个例子中的ZZZ跟在一长串A的后面呢?

回复 小河马 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

昵称 *