能否强制使用两行间距的文本小部件?

11

我需要找到一种方法,强制Flutter的Text小部件使用两行文本空间,即使只有一行。 例如,在下面的照片中,由于Text小部件仅使用一行空间,一个卡片比另一个卡片低。

输入图像描述

是否有人知道一些技巧,可以强制Text小部件使用maxLines空间,即使只需要一行?

6个回答

32

目前向Text添加minLines功能仍是一个待开发请求。您可以在这里进行跟踪。

暂时的解决方法是使用:

str = 'example'; 

Text(
  str + '\n',
  maxLines: 2,
)

非常干净的解决方案!非常感谢。 - Sanmeet

10

你可以使用\n来设置最小行数(这是一个技巧)

这个问题仍然存在 Github: 添加minLines到Text (flutter issue)

          Text(
            '${product.name}\n\n', //equal minlines: 3
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
            style:
                const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),

1
你可以在 TextStyle 中简单地使用 height 属性:
Text(
  "Some lines of text",
  style: TextStyle(
    fontSize: 14.0,
    height: 1.5 //set height as you want
  )
)

另一种选择是使用Spacer()
Row(
  children: <Widget>[
    Text('Begin'),
    Spacer(), // Defaults to a flex of one.
    Text('Middle'),
    // Gives twice the space between Middle and End than Begin and Middle.
    Spacer(flex: 2),
    Text('End'),
  ],
)

您可以在官方文档中找到有关Spacer的更多详细信息。


0

这是我找到的最佳解决方案。

您可以在一个地方设置所有文本样式,并像这样获取它

static TextStyle subtitle2(Color color) =>
  initStyle(color, 14.0, FontWeight.w600);

static TextStyle initStyle(
 Color color, 
 double fontSize, 
 FontWeight fontWeight) =>
  TextStyle(
      height: 1.2,
      fontSize: fontSize,
      color: color,
      fontWeight: fontWeight,
      fontFamily: 'OpenSans');

不要忘记设置文本样式的高度属性

然后你可以像这样定义你的文本

TextStyle textStyle = AppTextStyle.headline6(AppColors.onBackground);
int lines = 3;
...
Container(
      height: textStyle.height! * textStyle.fontSize! * lines,
      child: Text('Title', style: textStyle))

对我来说完美无缺

在此输入图片描述


0

试试这个,它会有效的。

Row(
     children: [
         Expanded(
           flex: 1,
           child: Text(
              'Your long text goes here, you can add as much as you want',
              maxLines: 2,   /// you can change it on your requirements, or may be ignore it
              ),
      )
    ],
)

0
一个不需要设置maxLines的解决方法是将Text放置在一个Stack中,与另一个(几乎)相同样式(除了透明)的Text一起,该Text具有确切的n行。
这样,Flutter会同时绘制两个文本,并且它所占用的空间将取决于哪个文本占用的行数更多。作为额外的好处,您还可以对显示的文本进行对齐,使其居中(例如)。
return Stack(
  alignment: Alignment.center,
  children: [
    Text(
      "\n\n\n",
      style: Theme.of(context).textTheme.bodyMedium.copyWith(
            color: Colors.transparent,
      ),
    ),
    Text(
      "Single Line of Text",
      style: Theme.of(context).textTheme.bodyMedium,
    ),
  ],
);

如果我有一个UI的一小部分,其中的文本在几个可能的值之间变化,并且我不希望包含它的容器每次都改变大小,我会经常这样做。适用于按钮、芯片、段落等等。而且还适用于用户的字体缩放和文本的任何翻译。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接