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

0

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): ^
flutter
formatexception
radix
asked on Stack Overflow Mar 5, 2020 by Max Walters

2 Answers

0

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.

answered on Stack Overflow Mar 5, 2020 by Naslausky
0

Sometimes we have to work with string in radix number format. Dart int parse() method also supports convert string into a number with radix in the range 2..36:

For example, we convert a Hex string into int:

var n_16 = int.parse('FF', radix: 16);
// 255
answered on Stack Overflow Jan 29, 2021 by Paresh Mangukiya

User contributions licensed under CC BY-SA 3.0