Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set Text Widget style with method rather than constructor

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading