简体   繁体   English

如何在 flutter 中创建一个只有两行文本的文本小部件?

[英]How to create a Text widget with exactly two lines of text in flutter?

I want to create a Text widget with exactly two lines of text even if text's length is too small or too large.即使文本的长度太小或太大,我也想创建一个只有两行文本的Text小部件。

I can limit upper-bound of line count with maxLines like below:我可以使用maxLines限制行数的上限,如下所示:

Text(subtitle,
    maxLines: 2,
    style: Theme.of(context).textTheme.bodyText1?.copyWith(
        color: Theme.of(context).colorScheme.onSurface,
        fontWeight: FontWeight.w400,
    )
)

I saw some answers where it is suggested to use a SizedBox to fix the height of content.我看到了一些建议使用SizedBox来固定内容高度的答案。 I didn't feel right to hardcode this value.我觉得硬编码这个值是不对的。

I am looking for something like lines in Android's TextView .我正在寻找类似 Android 的TextView中的lines What else can I do to achieve this in Flutter?在 Flutter 中我还能做些什么来实现这一点?

Update:更新:

From the help of comments & answers below, I am using following code now:在下面的评论和答案的帮助下,我现在使用以下代码:

static String enforceLineCount(String text, int lines) {
    String nextLineCharacters = "";
    for (int index = 0; index < (lines - 1); index++) {
        nextLineCharacters += "\n";
    }
    return text + nextLineCharacters;
}
Text(subtitle+'\n',   
    maxLines: 2,
    style: Theme.of(context).textTheme.bodyText1?.copyWith(
        color: Theme.of(context).colorScheme.onSurface,
        fontWeight: FontWeight.w400,
    )
)

the line break \n is a placeholder for 2 lines.换行符\n是 2 行的占位符。 The subtitle shift them down... and the maxLines condition is cutting them away:-) subtitle将它们向下移动......并且maxLines条件正在将它们切掉:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM