Flutter:如何根据可用空间裁剪文本?

Dar*_*han 4 text widget overflow dart flutter

如何根据可用空间裁剪文本?

有一个类似的问题在这里,但没有工作的答案。

目前,此代码

            return new GridTile(
              child: new Card(
                elevation: 3.0,
                child: new Container(
                  padding: new EdgeInsets.all(10.0),
                  child: new Column(
                    children: <Widget>[
                      Text(
                        document['title'],
                        style: new TextStyle(fontWeight: FontWeight.bold),
                      ),
                      Text(
                        document['text'],
                      ),
                    ],
                  ),
                ),
              )
            );
Run Code Online (Sandbox Code Playgroud)

给出了这个结果:

在此处输入图片说明

我尝试使用overflow: TextOverflow.ellipsis,但文本变成 1 行长。指定文本行长度是一个坏主意,因为在不同的屏幕尺寸上结果会有所不同。

如何使文本裁剪、适合或包裹到可用空间中?

Gün*_*uer 8

设置overflow行为应该做

  new Text(
    widget.text,
    // softWrap: true,
    overflow: TextOverflow.fade,
  )
Run Code Online (Sandbox Code Playgroud)

另请参阅Flutter:如何在特定长度内隐藏或显示更多文本

  • https://github.com/flutter/flutter/issues/15465#issuecomment-382458700 看起来与您似乎试图完成的事情相似,也许它包含一些有用的东西。 (2认同)
  • @GünterZöchbauer 它可以工作,但您还需要将“maxLines: 1”添加到您的“Text”。但问题是它垂直淡化文本,我正在寻找水平。你能帮我吗?编辑:设置 `softWrap: false` 似乎有效。 (2认同)

小智 5

将文本小部件包裹在“扩展”或“灵活”小部件内,并使用“overflow.ellipsis”,这对我有用

Column(
    children: <Widget>[
         Flexible(
             child: Text(
             "Some Very long Text or random generated strings ",
             overflow: TextOverflow.ellipsis,
             softWrap: true,
             ),
        ),
    ],
 ),
Run Code Online (Sandbox Code Playgroud)