Android 有可怕的表情符号。我可以在 Android 版 Flutter 中使用 Apple 的表情符号字体(就像 Telegram 和 WhatsApp 过去使用的那样)吗?
编辑:我的第一个猜测是添加字体,但由于我不想更改所有其他字体,所以我不确定这是否可行。
最佳答案
目前无法在 Flutter 中仅针对表情符号(或仅针对指定字符)定义自定义字体。有一个open Github issue关于这个。
但是,有一个技巧可以在文本小部件中混合您的字体和表情符号的另一种字体。我找到了答案here来做到这一点。
以下是您可以遵循的步骤:
- 您需要选择要使用的表情符号字体。我最喜欢的是 Joypixels : https://www.joypixels.com/fonts
- 按照文档下载字体 .ttf 并将其添加到您的项目中: https://flutter.dev/docs/cookbook/design/fonts
- 将此代码添加到您的项目中:
class TextWithEmojis extends StatelessWidget {
const TextWithEmojis({
Key? key,
required this.text,
required this.fontSize,
required this.color,
}) : super(key: key);
final String text;
final double fontSize;
final Color color;
@override
Widget build(BuildContext context) {
return RichText(
text: _buildText(),
);
}
TextSpan _buildText() {
final children = <TextSpan>[];
final runes = text.runes;
for (int i = 0; i < runes.length; /* empty */) {
int current = runes.elementAt(i);
// we assume that everything that is not
// in Extended-ASCII set is an emoji...
final isEmoji = current > 255;
final shouldBreak = isEmoji ? (x) => x <= 255 : (x) => x > 255;
final chunk = <int>[];
while (!shouldBreak(current)) {
chunk.add(current);
if (++i >= runes.length) break;
current = runes.elementAt(i);
}
children.add(
TextSpan(
text: String.fromCharCodes(chunk),
style: TextStyle(
fontSize: fontSize,
color: color,
fontFamily: isEmoji ? 'Joypixels' : null,
),
),
);
}
return TextSpan(children: children);
}
}
- 您现在可以在需要时使用 TextWithEmojis:
TextWithEmojis(
text: "Hello 👋 😄",
fontSize: 12,
color: Colors.white
)
关于flutter - 在 Android 中更改 Flutter 的表情符号字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67011139/