S.D.
S.D.

Reputation: 5867

Adding extra padding to TextSpan background in RichText widget

I have a RichText with some TextSpan. I want one of the TextSpan widgets to have a background on it so I used background: Paint()..color = Colors.redAccent as its text style.

Is there a way to add some extra red space/padding to the background.

This is how it currently looks:

before padding on text

This is how I want it to look (notice the extra red on the top and bottom of the highlighted text):

after padding on text (desired)

This is the code used:

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.
)

I tried adding height to the text style, but it doesn't affect the height of the background.

Upvotes: 27

Views: 27346

Answers (3)

Gabriel Costa
Gabriel Costa

Reputation: 196

you can use widgetSpan that inside RichText so that you can add any widget inside RichText.

RichText(
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          text: TextSpan(
            text: "text one", // text of exemple
            children: [

              // add a space between texts
              WidgetSpan(
                child: Padding(
                  padding: const EdgeInsets.only(left: 10.0),
                ),
              ),

              TextSpan(
                text: "text two", // text exemple
              ),
            ],
          ),
        ),

Upvotes: 3

Tokenyet
Tokenyet

Reputation: 4291

The new solution in 2019 with flutter 1.7.8 is WidgetSpan, you could just add a Container and a Padding or any combination of widget to make more variety!

Here is an example to use on the case:

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

And don't forget to change <TextSpan>[] to <InlineSpan>[], that's It!

Upvotes: 44

Andrii Turkovskyi
Andrii Turkovskyi

Reputation: 29438

Quite ugly solution, but I haven't found other (

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

strokeWidth have to be big enough to cover height of text. In my case 16.5 is minimal suitable value

Upvotes: 12

Related Questions