Home > Back-end >  Set Text Widget style with method rather than constructor
Set Text Widget style with method rather than constructor

Time:08-20

I'd like to be able to instantiate a Text Widget with many proprieties & create a new instance from it but with a new TextStlye by just calling a method on it like so :

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

  final Text myTextWithNewStyle = myText.setNewStyle();

I thought of using an extension on Text but I'm not sure on how to keep all of it's current parameter values

CodePudding user response:

You can update style like this if it works for you:

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

or

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);
  }
}

and use it like this:

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