Home > database >  Flutter if statement in a custom class
Flutter if statement in a custom class

Time:07-30

I have a class like this:

    import 'package:flutter/material.dart';

class myTextStyle extends TextStyle {
  final Color color;
  final double size;
  final String fontFamily;
  final bool bold;

  const myTextStyle({
    required this.size,
    this.color = Colors.black87,
    this.fontFamily = 'OpenSans',
  })
      : assert(size != null),
        super(
        color: color,
        fontSize: size,
        fontFamily: fontFamily,
      );
}

I want to add a if statement for bold. İf bold==true a want to make Fontweigh=Fontweight.bold. Can someone help me? Thanks.

CodePudding user response:

this.FontWeight = bold ? FontWeight.bold : FontWeight.normal

I belive this is what you are looking for. It is called ternary operator.

class myTextStyle extends TextStyle {
  final Color color;
  final double size;
  final String fontFamily;
  final FontWeight fontWeight;  
  const myTextStyle({
    @required this.size,
    this.color = Colors.black87,
    this.fontFamily = 'OpenSans',
    this.fontWeight = FontWeight.normal,
  })  : assert(size != null),
        super(
          color: color,
          fontSize: size,
          fontFamily: fontFamily,
          fontWeight: fontWeight
        );
}

I think you should do it like that and then in your widget when you call your myTextStyle use this ternary operator.

The const keyword is used when the value of the variable is known at compile-time and never changes. In other words, the compiler knows in advance what value is to be stored in that variable. const int x = 1;//At compile time, the value of x is going to be 1 and will not change

so since myTextStyle is const you cannot use dynamic values there because at compile time you dont have it yet.

  • Related