fluttercolorsdeprecation-warning

Warnings after upgrading to Flutter 3.27.0: 'value' and 'green' are deprecated


After upgrading Flutter to version 3.27.0, I started seeing some warnings related to deprecated properties in the Color class:

Warning:

info: 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g. (deprecated_member_use)

This warning is for the following code snippet:

String get colorHexString => color.value.toRadixString(16).substring(2);

Warning:

info: 'green' is deprecated and shouldn't be used. Use .g. (deprecated_member_use)

This warning is for this part of the code:

String toHex({bool hashSign = false, bool withAlpha = false}) =>
  '${hashSign ? '#' : ''}'
          '${_generateAlpha(alpha: alpha, withAlpha: withAlpha)}'
          '${red.toRadixString(16).padLeft(2, '0')}'
          '${green.toRadixString(16).padLeft(2, '0')}'
          '${blue.toRadixString(16).padLeft(2, '0')}'
      .toUpperCase();

Solution

  • The following solutions worked for me:

    1. colorHexString Getter:

    This method constructs the hex string for a Color object, including its alpha value:

     String get colorHexString {
        final red = (color.r * 255).toInt().toRadixString(16).padLeft(2, '0');
        final green = (color.g * 255).toInt().toRadixString(16).padLeft(2, '0');
        final blue = (color.b * 255).toInt().toRadixString(16).padLeft(2, '0');
        final alpha = (color.a * 255).toInt().toRadixString(16).padLeft(2, '0');
    
        return '$alpha$red$green$blue';
      }
    
    1. toHex Method:

    This method generates a hex string for a Color object with optional parameters for including a hash sign (#) and alpha transparency:

       String toHex({bool hashSign = false, bool withAlpha = false}) {
        final alpha = (a * 255).toInt().toRadixString(16).padLeft(2, '0');
        final red = (r * 255).toInt().toRadixString(16).padLeft(2, '0');
        final green = (g * 255).toInt().toRadixString(16).padLeft(2, '0');
        final blue = (b * 255).toInt().toRadixString(16).padLeft(2, '0');
    
        return '${hashSign ? '#' : ''}'
                '${withAlpha ? alpha : ''}'
                '$red$green$blue'
            .toUpperCase();
      }