如何更改现有TextStyle的特定属性?

时间:2019-08-16 21:09:12

标签: flutter dart

我想制作一个自定义窗口小部件,该结构基本上是通过获取文本,将笔画添加到文本中,将其包装在具有两个文本的堆栈中,其中一个用笔画呈现。

class BorderedText extends StatelessWidget {
  final Text displayText;
  final Color strokeColor;
  final double strokeWidth;

  BorderedText(this.displayText,
      {Key key, this.strokeColor = Colors.black, this.strokeWidth = 1.0})
      : assert(displayText != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          Text(
            displayText.data,
            style: displayText.style
              ..foreground = Paint()
                ..style = PaintingStyle.stroke
                ..strokeWidth = strokeWidth
                ..color = strokeColor,
          ),
          displayText,
        ],
      ),
    );
  }
}

预期的使用方式:

BorderedText(
  Text(
    "Hello App",
    style: TextStyle(
      color: Colors.white,
      fontSize: 34.0,
      fontFamily: "LexendMega",
    ),
  ),
  strokeWidth: 6.0,
),

可悲的是,此代码不起作用,因为foreground是最终的。我该怎么解决?

  • 我可以复制displayText参数并能够更改其foreground吗?
  • 我能否仅更改前景而制作其TextStyle的副本?

1 个答案:

答案 0 :(得分:3)

您可以使用TextStyle.copyWith。这将从其他文本样式复制参数,并且仅更改您提供的参数。在您的情况下,它看起来像这样:

Text(
  displayText.data,
  style: displayText.style.copyWith(
      foreground: Paint()
        ..style = PaintingStyle.stroke
        ..strokeWidth = strokeWidth
        ..color = strokeColor
  ),
)

顺便:该方法在Flutter框架中的许多类中都存在(在这种情况下很有意义),它非常有用,因为您需要手动键入所有参数。