我想制作一个自定义小部件,它基本上通过获取一个文本来为文本添加笔划,将其包装在一个包含两个文本的 Stack 中,其中一个用笔划渲染。
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
,只改变前景吗?
最佳答案
您可以使用 TextStyle.copyWith
为了这。这将从您的其他文本样式复制参数,并且仅更改您提供的参数。在您的情况下,它看起来像这样:
Text(
displayText.data,
style: displayText.style.copyWith(
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth
..color = strokeColor
),
)
顺便说一下:Flutter 框架中的许多类都存在此方法(在有意义的地方),它非常有用,否则您将需要手动输入所有参数。
关于flutter - 如何更改现有 TextStyle 的特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57531166/