【问题标题】:Adding extra padding to TextSpan background in RichText widget在 RichText 小部件中向 TextSpan 背景添加额外的填充
【发布时间】:2019-03-04 23:26:57
【问题描述】:

我有一个RichText 和一些TextSpan。我希望其中一个TextSpan 小部件具有背景,因此我使用background: Paint()..color = Colors.redAccent 作为其文本样式。

有没有办法在背景中添加一些额外的红色空间/填充。

这是它目前的样子:

这就是我想要的样子(注意突出显示文本顶部和底部的额外红色):

这是使用的代码:

Scaffold(
  appBar: new AppBar(),
  body: new RichText(
    text: new TextSpan(
      text: 'This is a one the lines in the span \n ',
      style: TextStyle(fontSize: 15.0, color: Colors.black),
      children: <TextSpan>[
        new TextSpan(
            text: 'This is the second line',
            style: new TextStyle(fontWeight: FontWeight.bold)),
        new TextSpan(
            text: ' background on me ',
            style: new TextStyle(
              fontWeight: FontWeight.bold,
              background: Paint()..color = Colors.redAccent,
            )),
        new TextSpan(text: ' This is another of the lines in the span!'),
      ],
    ),
  ), // This trailing comma makes auto-formatting nicer for build methods.
)

我尝试在文本样式中添加height,但它不影响背景的高度。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    相当丑陋的解决方案,但我还没有找到其他(

    TextStyle(fontWeight: FontWeight.bold,
      background: Paint()..color = Colors.redAccent
        ..strokeWidth = 16.5
        ..style = PaintingStyle.stroke,)
    

    strokeWidth 必须足够大以覆盖文本的高度。在我的情况下,16.5 是最小的合适值

    【讨论】:

    • 我在文本上得到一个strikeThough,如果我申请PaintingStyle.stroke
    【解决方案2】:

    2019 年 Flutter 1.7.8 的新解决方案是 WidgetSpan,您可以添加一个 Container 和一个 Padding 或任何小部件的组合以增加多样性!

    这是一个用于案例的示例:

    WidgetSpan(
      child: Container(
        color: Colors.red,
        padding: EdgeInsets.all(8.0),
        child: Text("background on me", style: ...),
      )
    )
    

    别忘了把&lt;TextSpan&gt;[]改成&lt;InlineSpan&gt;[],就是这样!

    【讨论】:

    • 如果文本跨行并且填充只需要应用于行的一部分,这将不起作用
    • @Arpit 你不能使用 letterSpacing(在 TextStyle 中)在行间填充吗?
    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多