Flutter:如何在文本中添加图标?

29

我想在文本中添加一个图标,但没有找到明确的答案。请建议我如何在Flutter中实现这一点。就像这个例子一样。

Desired image

2个回答

82

这里有两种方法,具体取决于您想要的内容。

使用WidgetSpan的RichText

使用RichText,您可以将TextSpans与WidgetSpans混合使用。 WidgetSpan允许您在文本中与任何Flutter widget一起内联放置。例如:

RichText(
  text: TextSpan(
    style: Theme.of(context).textTheme.body1,
    children: [
      TextSpan(text: 'Created with '),
      WidgetSpan(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 2.0),
          child: Icon(Icons.airport_shuttle),
        ),
      ),
      TextSpan(text: 'By Michael'),
    ],
  ),
)

将会得到以下结果:

在此输入图片描述

(注意: 当我回答时,MaterialIcons并没有包含一个心形图标,但现在有了 Icons.favorite)

这是一个很好的通用解决方案,但对于您的具体示例,有一些更简单的方法...

表情符号

Flutter 的文本支持表情符号。因此,您可以这样做:

Center(
  child: Text(
    'Created with ❤ ️by Michael',
    maxLines: 1,
  ),
),

然后你会得到这个:

enter image description here

你也可以在字符串中使用Unicode转义,得到相同的结果:

'Created with \u2764️ by Michael'
请注意,并非所有字体都支持完整的表情符号集,因此请确保在多种设备上进行测试或使用特定字体(请参见下面的其他答案)。

3

关于表情符号,在Android中不是所有的表情符号都被支持(取决于操作系统版本)。

为了实现完整的表情符号兼容性,您可以使用Google免费的Noto Color Emoji字体,网址为:https://www.google.com/get/noto/#emoji-zsye-color

  • 将其添加到字体文件夹中
  • 在pubspec.yaml文件中添加
    fonts:
    - family: NotoEmoji
      fonts:
        - asset: fonts/NotoColorEmoji.ttf
          weight: 400
  • 与TextStyle一起使用

    Text("", TextStyle(fontFamily: 'NotoEmoji'))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接