【问题标题】:How to add padding to background color of text widget如何为文本小部件的背景颜色添加填充
【发布时间】:2020-11-22 06:38:45
【问题描述】:

我想创建一个文本小部件来实现您在下面看到的效果:

我希望文本的背景颜色有一些额外的填充,但仅限于实际存在文本的位置。

目前,我必须选择将文本小部件包装在容器小部件中(然后将背景颜色添加到第二个较短行的空白区域,这是我不想要的)。或者,我可以选择为文本的 textStyle 小部件使用背景颜色,但它不尊重高度(又名行高)。

有没有办法做到这一点?

【问题讨论】:

  • @rexfordkelly 感谢您的回复,但不,这是针对 CSS 的。我正在尝试通过 Flutter 实现这一目标。

标签: flutter dart flutter-layout


【解决方案1】:

这两个答案都是 hack,它们根本不能很好地适应较大的文本。 因此,我编写了一个包,它现在能够为文本背景添加填充、半径和颜色。

这是包装文本的确切功能的图像:

包的链接如下:https://github.com/Letalus/auto_size_text_background

【讨论】:

  • 感谢您的回答!我刚刚尝试了这个包,发现没有调整填充或舍入的选项 - 你能帮我解决这个问题吗?
  • 好点,我还没有将这两个参数发布到 AutoSizeText 小部件。很快就会做。重要提示:由于计算文本宽度和高度的新问题,背景目前不稳定。我正在修复。一旦我解决了根本问题,我将在此处更新包和我的描述。
【解决方案2】:

您可以将Paint 用于backgroundTextStyle

Text(
  'Random caption for this post1',
  style: TextStyle(
    fontWeight: FontWeight.bold,
    background: Paint()..color = Colors.white
    ..strokeWidth = 17
    ..style = PaintingStyle.stroke,
  ),
  textAlign: TextAlign.center,
)

结果:

【讨论】:

  • 我在 Flutter 2.5.2 上面的文字上得到一个strikeThrough
【解决方案3】:

为此,您可以使用Column() 并为单个帖子文本添加两个Containers(),并使用以下代码规范

        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //this is first container
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.white),
                borderRadius: BorderRadius.circular(10.0)
              ),
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Text("This is the dummy text for", style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold))
              )
            ),
            
            //this is second container
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.white),
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10.0), bottomRight: Radius.circular(10.0))
              ),
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Text("post 1", style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold))
              )
            )
          ]
        )

结果

【讨论】:

  • 感谢您的回答。这确实实现了这种风格,但我认为这种方法必须是硬编码的。我需要一些更流畅并且可以自行缩放的东西,例如,不同的字幕长度。
  • 是的,即使我也在寻找它,但不知何故需要时间。让我看看我能不能想出点什么来。 @Chrisl446 :)
猜你喜欢
  • 2019-06-17
  • 1970-01-01
  • 2013-01-15
  • 2023-03-24
  • 1970-01-01
  • 2011-01-19
  • 2011-01-29
  • 1970-01-01
  • 2022-11-01
相关资源
最近更新 更多