Home > Software engineering >  Flutter parse unicode characters not working
Flutter parse unicode characters not working

Time:07-09

I have the following string coming from my backend server \u25CF\u25CF\u25CF and when I decode it with UTF-8 it's working fine in the iOS native app, But when I try to parse it in flutter I'm not able to get the converted value. I have tried the following approaches but none worked

String converted = Utf8Decoder().convert(userName.codeUnits);
String uname = utf8.decode(userName.runes.toList());
String runes = String.fromCharCodes(Runes('$userName'));

Does anyone know how we can fix this? The real value should be 3 dots after conversion.

CodePudding user response:

Consider using the characters package instead of runes. Seems like it can solve your problem.

CodePudding user response:

You are starting with a string with unicode escapes and you want to end up with a string containing the actual unicode characters. This is easy if the input contains only unicode escapes as you can simply strip out the \u and parse the hex to a code point.

  final input = '\\u25CF\\u25CF\\u25CF'; // note I have to double the \ as this is source code
  var hexPoints = input.split('\\u').sublist(1);
  print(hexPoints); // [25CF, 25CF, 25CF]

  // convert to a string from codepoints, parsing each hex string to an int
  final result = String.fromCharCodes(
    hexPoints.map<int>((e) => int.parse(e, radix: 16)).toList(),
  );
  print(result); // dot, dot, dot

It's a bit tricker if you have to find escaped characters inside normal characters. Then you can iterate along the string to find any occurrences of \u, swallow those two characters, parse the next 4 chars as hex and emit that code point.

  • Related