I have a RichText widget that contains some TextSpan. Around a TextSpan widget I want to place a border around it.

RichText(
  text: TextSpan(
    style: textStyle,
    children: [ ], // code has more TextSpan widgets as children
  ),

This is an example of the effect I am trying to achieve in Flutter.

border around text


Solution 1: Andrey Turkovsky

Paint paint = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = 2.0;

RichText( text: TextSpan(children: [ TextSpan(text: '123'), TextSpan(text: '456', style: TextStyle(background: paint)), TextSpan(text: '789') ]))


Solution 2: Larry McKenzie

Use a WidgetSpan if you want to do more interesting things like add padding.

Text.rich(
  TextSpan(
    text: 'Lorem ipsum',
    children: [
      WidgetSpan(
        alignment: PlaceholderAlignment.middle,
        baseline: TextBaseline.ideographic,
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 2),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.blue, width: 1),
          ),
          child: const Text('dolor sit amet,'),
        ),
      ),
      const TextSpan(text: 'consectetur'),
    ],
  ),
);