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;

  Widget build(BuildContext context) {
    var textTheme = Theme.of(context).textTheme;
    var style = getThemeProperty(type, textTheme);
    return 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

final type;
final text;
final color;

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
// DO

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top