Home > front end >  Flutter apply method to static variable
Flutter apply method to static variable

Time:10-17

How do you apply a method to a static variable from a class. There are certain built in classes in flutter that appear to do something like this.

class UITextStyle {
  static const TextStyle body = TextStyle(fontSize: 17);

   addColor(Color color) {
    TextStyle style = this as TextStyle;
    style.merge(TextStyle(color: color));
  }
}

Which can then be called like this:

UITextStyle.body.addColor(Color.fromRGBA(0,0,0,1));

However I cannot call that method like that as firstly it is not static, and secondly if it were I would not be able to call it after declaring .body first and would only be able to call it at UITextStyle.addColor(...).

How is this achieved?

CodePudding user response:

you can try this solution , the point is that addColor function is not defined to the TextStyle Type , so to achieve that you need to add this function to the TextStyle class by this extension :

extension TextStyleEx on TextStyle{

  TextStyle addColor(Color color) {
    return merge(TextStyle(color: color,fontWeight: FontWeight.w600));
  }

}

and make this method return TextStyle so you can get instance from the merged ones , cause your static object is final so you can not receive new value on it.

  • and leave your class like this

      class UITextStyle {
        static const TextStyle body = TextStyle(fontSize: 17);
      }
    
  • use this class and the saved static object to get new TextStyle with the old and the new TextStyles.

  • for test run this in main , will clear the previous example :

    TextStyle mergedStyles = UITextStyl.body.addColor(Colors.black);
    print(mergedStyles);
    

CodePudding user response:

Thanks to the comments from @pskink I was eventually able to get this functioning.

class UITextStyle {
  const UITextStyle(this.style);
  final TextStyle style;
  static const body = UITextStyle(TextStyle(fontSize: 17));

  addColor(Color color) {
    TextStyle textStyle = style;
    return textStyle.merge(TextStyle(color: color));
  }
}

CodePudding user response:

In Dart extensions can have static members.

extension UITextStyle on TextStyle {
  static const body = TextStyle(fontSize: 17);
  
  TextStyle addColor(Color color) {
    return this.merge(TextStyle(color: color));
  }
}

You can then do:

UITextStyle.body.addColor(Color.fromRGBO(0, 0, 0, 1));
  • Related