首页 > 解决方案 > 如何更改现有 TextStyle 的特定属性?

问题描述

我想制作一个自定义小部件,该小部件基本上通过获取文本来向文本添加笔触,将其包装在包含两个文本的堆栈中,其中一个以笔划呈现。

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它是最终的。我该如何解决这个问题?

标签: flutterdart

解决方案


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

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

顺便说一句:这种方法存在于 Flutter 框架中的许多类中(它是有意义的),它非常有用,因为您需要手动键入所有参数,否则。


推荐阅读