safeDecodeUriComponent function
Decodes a percent-encoded URI component without throwing on malformed UTF-8 sequences. Invalid escapes are kept as-is and invalid UTF-8 bytes are replaced with the Unicode replacement character (�).
Implementation
String safeDecodeUriComponent(String component) {
try {
return Uri.decodeComponent(component);
} on FormatException {
final bytes = <int>[];
for (var i = 0; i < component.length; i++) {
final char = component[i];
if (char == '%' && i + 2 < component.length) {
final hex = int.tryParse(component.substring(i + 1, i + 3), radix: 16);
if (hex != null) {
bytes.add(hex);
i += 2;
continue;
}
}
bytes.addAll(utf8.encode(char));
}
return utf8.decode(bytes, allowMalformed: true);
}
}