flutter中如何正确处理包含表情符号emoji的字符串?

码云
2020-11-12 17:32

当我们处理的字符串中包含表情符号(如:👋、👏等)的时候,会发现字符串常用的方法(length substring replaceAll等)返回结果都不对。归根到底是表情符号Emoji占用的长度与普通字符不一致导致。为解决问题需要引入character包来处理。

  • 导入依赖包
dependencies:
  characters: ^1.0.0

 

  • 示例代码
import 'package:characters/characters.dart';

void main() {
  String hi = 'Hi 👌😡';
  print('String is "$hi"\n');

  // Length.
  print('String.length: ${hi.length}');
  print('Characters.length: ${hi.characters.length}\n');

  // Last character.
  print('The string ends with: ${hi.substring(hi.length - 1)}');
  print('The last character: ${hi.characters.last}\n');

  // Skip last character.
  print('Substring -1: "${hi.substring(0, hi.length - 1)}"');
  print('Skipping last character: "${hi.characters.skipLast(1)}"\n');

  // Replace characters.
  Characters newHi =
  hi.characters.replaceAll('👌'.characters, '🤝'.characters);
  print('Change flag: "$newHi"');
}

 

  • 打印结果

通过上面的输出内容可以看出characters可以正确处理包含表情的字符串。

全部评论