Reputation: 672
I want to make a custom widget that basically adds a stroke to a text by taking a Text, wrapping it in a Stack with two texts, with one of them rendered with a stroke.
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,
],
),
);
}
}
Intended way of usage:
BorderedText(
Text(
"Hello App",
style: TextStyle(
color: Colors.white,
fontSize: 34.0,
fontFamily: "LexendMega",
),
),
strokeWidth: 6.0,
),
Sadly this code doesn't work because foreground
is final. How can I address that?
displayText
parameter and be able to change its foreground
?TextStyle
, only changing the foreground?Upvotes: 5
Views: 1814
Reputation: 126694
You can use TextStyle.copyWith
for this. This will copy the parameters from your other text style and only changes the ones you supply. In your case it would looks like this:
Text(
displayText.data,
style: displayText.style.copyWith(
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth
..color = strokeColor
),
)
By the way: this method exists for many classes in the Flutter framework (where it makes sense) and it is very useful as you would need to manually type all the parameters otherwise.
Upvotes: 12