flutter add a simple wrapper to the text widget

The reason why the dart compiler is unhappy is just because the color property of the TextStyle is declared as final. Therefore to use a new color, you have to create a new instance of the TextStyle.

Luckily, the TextStyle class comes with a copyWith method that returns an edited copy of your TextStyle

  final type;
  final text;
  final color;

  @override
  Widget build(BuildContext context) {
    var textTheme = Theme.of(context).textTheme;
    var style = getThemeProperty(type, textTheme);
    
    return Text(
      this.text,    
      // Added this...
      style: style.copyWith(color: color ?? style.color),
    );
  }

As a side note, when making reusable widgets, it’s always a good idea to type your parameters. This is because any type of variable can be used. So instead of passing a String for text, you may pass an int

// DON'T DO THIS
final type;
final text;
final color;

// DO THIS
final String type;
final String text;
final Color color;

Also adding the this keyword to reference a variable in a class without variable shadowing is unnecessary.

// DON'T
this.text
// DO
text

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top