在RichText小部件中为TextSpan背景添加额外的填充

S.D*_*.D. 8 dart flutter

我有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.
)
Run Code Online (Sandbox Code Playgroud)

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

Tok*_*yet 24

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: ...),
  )
)
Run Code Online (Sandbox Code Playgroud)

并且不要忘记更改<TextSpan>[]<InlineSpan>[],就是这样!

  • 如果文本跨行换行并且填充仅需要应用于行的一部分,则此方法不起作用 (3认同)

And*_*sky 6

非常难看的解决方案,但我还没有找到其他解决方案(

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

strokeWidth必须足够大以覆盖文本的高度。就我而言,16.5是最小的合适值