RichText的textSpan周围的边框

时间:2020-02-26 10:56:52

标签: flutter flutter-layout flutter-dependencies flutter-web

我有一个RichText小部件,其中包含一些TextSpan.小部件,在TextSpan周围,我想在其周围放置边框。另外,我希望它可以在网络上运行,但是目前从我的方法来看,这仅适用于移动设备。

预期:我想实现以下目标。 <code>enter image description here</code>

使用此代码的结果:

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

RichText(
   text: TextSpan(children: [
       TextSpan(text: text1),
       TextSpan(text: text2, style: TextStyle(background: paint)),
       TextSpan(text: text3, )
  ]))

请帮助!

如果不清楚,简单地说,我只想在突出显示的部分周围有一个边框,并删除下图中的突出显示,而无需进行其他更改

enter image description here

2 个答案:

答案 0 :(得分:1)

由于op的问题是在网络中发生的,由于flutter-web本身存在错误,因此目前尚无法解决。但是,以下是答案,其中包含一个通用解决方案,该解决方案在修复后即可在Flutter Web中工作。

新答案:2020年4月3日 为了获得所需的效果,必须在blendMode对象中使用BlendMode.difference选项,名为Paint。您可以使用它来实现与所需结果相似的结果。

enter image description here

相同的代码

 TextSpan(
          style: TextStyle(
            background: Paint()
              ..color = Colors.blue
              ..style = PaintingStyle.stroke
              ..strokeWidth = 2.0
              ..strokeJoin = StrokeJoin.bevel
              ..blendMode = BlendMode.difference,
          ),
          text:
              'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        ),

注意:我也正在尝试另一种手动绘制边界的艰辛方法。如果您遇到其他解决方案,请在此处共享。 :)希望对您有帮助。

旧答案

因此,根据运行时的上下文,我切换了文本样式。对于网络,它传递TextDecorations的列表,例如underlineoverline。这不会覆盖文本的结尾,但是我相信比结果中完全突出显示的文本更好。还有其他一些选项,例如decorationThicknessdecorationStyle

这是该解决方案在波动Web模式下的外观。

enter image description here

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

    return RichText(
      text: TextSpan(
        children: [
          TextSpan(text: 'bounded text1'),
          TextSpan(
            text: ' Will this work ',
            style: kIsWeb
                ? TextStyle(
                    decoration: TextDecoration.combine(
                        [TextDecoration.overline, TextDecoration.underline]),
                    decorationColor: Colors.blue,
                  )
                : TextStyle(
                    background: paint,
                  ),
          ),
          TextSpan(
            text: 'bounded text 3',
          )
        ],
      ),
    );

我将这些样式提取为一个常量,并根据当前正在运行的上下文(例如android或web)动态应用它们。希望这会有所帮助。

答案 1 :(得分:0)

您可以在这样的容器内使用文本

return Container(
        margin: const EdgeInsets.all(30.0),
        padding: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
    border: Border.all(),
  ), 
        child: Text(
          "text",
          style: TextStyle(fontSize: 30.0),
        ),
      );