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

Leo*_*Ven 3 dart flutter

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

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,
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

预期使用方式:

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

遗憾的是,这段代码不起作用,因为它foreground是最终的。我该如何解决?

  • 我可以制作displayText参数的完整副本并能够更改它foreground吗?
  • 我可以复制它的TextStyle,只改变前景吗?

cre*_*not 5

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

Text(
  displayText.data,
  style: displayText.style.copyWith(
      foreground: Paint()
        ..style = PaintingStyle.stroke
        ..strokeWidth = strokeWidth
        ..color = strokeColor
  ),
)
Run Code Online (Sandbox Code Playgroud)

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