使用方法而不是构造函数设置文本小部件样式



我希望能够实例化具有许多特性的文本小部件&从中创建一个新实例,但只需调用一个方法,就可以使用一个新的TextStlye,如下所示:

final Text myText = Text('hello', ...);
final Text myTextWithNewStyle = myText.setNewStyle();

我想过使用extension on Text,但我不确定如何保持它的所有当前参数值

如果对你有用,你可以更新这样的样式:

TextStyle defultStyle = TextStyle(color: Colors.red);
TextStyle newStyle = defultStyle.copyWith(color: Colors.blue)

extension TextExtension on Text {
Widget setNewStyle(TextStyle newStyle, {Key key}) {
return Text(this.data,
key: key,
style: newStyle,
strutStyle: this.strutStyle,
textAlign: this.textAlign,
textDirection: this.textDirection,
locale: this.locale,
softWrap: this.softWrap,
overflow: this.overflow,
textScaleFactor: this.textScaleFactor,
maxLines: this.maxLines,
semanticsLabel: this.semanticsLabel,
textWidthBasis: this.textWidthBasis,
textHeightBehavior: this.textHeightBehavior);
}
}

并像这样使用:

Text text = Text(
'dasdasd',
style: TextStyle(color: Colors.blue),
);
Widget newText = text.setNewStyle(TextStyle(color: Colors.red));

最新更新