如何在Flutter中动态调整文本大小? [英] How to dynamically resize text in Flutter?

查看:84
本文介绍了如何在Flutter中动态调整文本大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从API检索了一段文本.我想为其分配一定的空间(例如,一个最大容器的宽度为300.0,高度为100.0).有时,一段文本适合此Container,字体大小为30.0.在其他时候,除非我将文字大小设置为24.0,否则它就不合适.

I retrieve a piece of text from an API. I want to allot a set amount of space to it (say a max Container with width: 300.0 and height: 100.0). Sometimes, the piece of text fits in this Container with font size 30.0. In other times, it won't fit unless I set the text size to 24.0.

有没有一种方法可以根据其父容器空间动态调整文本大小?

Is there a way to dynamically resize text based on its parent container space?

我建立了一个带有ConstrainedBox的容器,它可以让我定义文本空间的最大大小.我还用LayoutBuilder包装了Text.我希望我可以检查文本空间的高度,并据此确定如何调整文本大小.像这样:

I've built a Container with a ConstrainedBox, which lets me define the max size of the text space. I've also wrapped my Text with a LayoutBuilder. I was hoping that I could check the height of the space of the text, and based on that, determine how to size the text. Like this:

    Container(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minWidth: 300.0,
          maxWidth: 300.0,
          minHeight: 30.0,
          maxHeight: 100.0,
        ),
        child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
          if (/* height is larger than 100.0? height is over the constraints? */) { return textWithSize24(); }
          return textWithSize30();
        }),
      ),
    ),

如何确定如果文本大小为30.0,则文本占据的高度"?也许我正以错误的方式来处理这个问题,而应该使用 maxLines 来确定呢?但是我们怎么知道我们已经达到了超过 maxLines 的范围?

How can I determine the "height that the text would take up if it were size 30.0"? Maybe I'm approaching this the wrong way and I'm supposed to use maxLines to determine this instead? But how do we know that we've reached more than maxLines?

另一种方法是使用字符串"中的字符数来确定何时更改字体大小.这似乎是手动的.

The other way to do it is to use the number of characters in my String to determine when to change font sizes. This seems kind of manual.

推荐答案

您可以使用 FittedBox 即可根据高度或宽度来管理文本.

You can use FittedBox to manage text based on height or width.

例如.

只需将您的 Text 小部件包装到 FittedBox 小部件中,在这里,我想根据宽度调整AppBar文本的大小.

Simply just wrap your Text widget to FittedBox widget like, Here I want to resize my AppBar text based on width.

AppBar(
    centerTitle: true,
    title: FittedBox(
        fit: BoxFit.fitWidth, 
        child: Text('Hey this is my long text appbar title')
    ),
),

文本将根据AppBar的宽度进行调整.

Text will be resized based on width of AppBar.

这篇关于如何在Flutter中动态调整文本大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆