flutterformatexceptionradix

FormatException: Invalid radix-16 number (at character 1)


I was able to pinpoint the issue to this function, but I'm unsure of how to fix it.

Color colorLuminance(String hex, double lum){
  // Verifying & extending hex length
  if (hex.length < 6) {
    hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  }

  // Convert to decimal and change luminosity
  var rgb = "", i;
    for (i = 0; i < 3; i++) {
        String x = hex.substring(i*2, 2);
        var c = int.parse(x, radix: 16);
        double a = c + (c * lum);
        double y = min(max(0, a), 255);
        x = y.round().toRadixString(16);
        rgb += ("00"+x).substring(x.length);
    }

  return Color(int.parse(rgb.substring(0, 7), radix: 16) + 0xFF000000);
}

It's running into a FormatException: Invalid radix-16 number (at character 1) with the line var c = int.parse(x, radix: 16);

I'm currently passing in Color(0xFFffffff) with this function:

String colorToString(Color c){
  String colorString = c.toString();
  String valueString = colorString.substring(10, colorString.length - 1);
  return valueString;
}

This is the output when I try flutter run:

I/flutter ( 7991): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 7991): The following FormatException was thrown building _BodyBuilder:
I/flutter ( 7991): Invalid radix-16 number (at character 1)
I/flutter ( 7991):
I/flutter ( 7991): ^

Solution

  • In this line:

    String x = hex.substring(i*2, 2);
    

    i will contain values from 0 to 2 (inclusive).

    So, when i=1or i=2, the startIndex will be equal or higher than the endIndex, and the substring will return empty.

    From the documentation:

    Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive.

    (The second parameter is the endIndex, not the length)

    So you should use:

    String x = hex.substring(i*2, (i*2)+2);

    To extract the r/g/b values separately from the hex code.