Flutter:如何在文字上添加图标?

Jay*_*llu 2 flutter flutter-layout

我想添加一个带有文本的图标。我没有找到明确的答案。请给我建议如何做到这一点。就这样。

所需的图像

Mic*_*elM 6

这有两种方法,具体取决于您要的是什么。

带有WidgetSpan的RichText

使用RichText,您可以将TextSpans与WidgetSpans混合使用。WidgetSpan允许您将任何Flutter窗口小部件与文本内联放置。例如:

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'),
    ],
  ),
)
Run Code Online (Sandbox Code Playgroud)

将给出以下内容:

在此处输入图片说明

(MaterialIcons不包含心脏)

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

表情符号

Flutter的文字支持开箱即用的表情符号。因此,您可以执行以下操作:

Center(
  child: Text(
    'Created with ? ?by Michael',
    maxLines: 1,
  ),
),
Run Code Online (Sandbox Code Playgroud)

你得到这个:

在此处输入图片说明

您还可以在字符串中使用Unicode转义并获得相同的结果:

'Created with \u2764? by Michael'
Run Code Online (Sandbox Code Playgroud)