0

I create a Style class in my flutter project. So I will use this Style class to call the TextStyle that I want to insert it in main.dart. I also create a constructor in Style class to get the color when the Style class called. I want to call the Style class in main.dart with Style(Colors.black).header . But there is an error while I try to create a constructor : enter image description here

I need your help to solve this error, thank you very much :)

Bill Rei
  • 333
  • 3
  • 14
  • `class Style { Color styleColor; Style(this.styleColor); final TextStyle header = TextStyle( color: Colors.white, fontSize: 24, fontFamily: "Poppins", fontWeight: FontWeight.w700, ); }` – Bill Rei Apr 17 '21 at 01:15

1 Answers1

3

You can't access other instance members styleColor from the initializer of another. To solve this, you need to delay the initialization of header in some way, which could be accomplished by using the initializer list or making header a getter.

Using initializer list:

class Style {
  Color styleColor;
  
  Style(this.styleColor) : 
    header = TextStyle(
      color: styleColor,
      fontSize: 24,
      fontFamily: "Poppins",
      fontWeight: FontWeight.w700,
    ),
    title1 = TextStyle(
      color: styleColor,
      fontSize: 24,
      fontFamily: "Poppins",
      fontWeight: FontWeight.w700,
    );
  
  final TextStyle header;
  final TextStyle title1;
}

Making header a getter:

class Style {
  Color styleColor;
  
  Style(this.styleColor);
  
  TextStyle get header => TextStyle(
    color: styleColor,
    fontSize: 24,
    fontFamily: "Poppins",
    fontWeight: FontWeight.w700,
  );

  TextStyle get title1 => TextStyle(
    color: styleColor,
    fontSize: 24,
    fontFamily: "Poppins",
    fontWeight: FontWeight.w700,
  );
}
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52