Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: how to add icon to text?

Tags:

I want to add an icon with text. I didn't find any clear answer. Please suggest to me how to do this in a flutter. Just like this one.

Desired image

like image 432
Jay Tillu Avatar asked Sep 11 '19 23:09

Jay Tillu


2 Answers

Here are two approaches, depending on exactly what you want.

RichText with WidgetSpan

Using RichText you can mix TextSpans with WidgetSpans. WidgetSpan allows you to place any Flutter widget inline with the text. For example:

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'),
    ],
  ),
)

Will give the following:

enter image description here

(MaterialIcons does not include a heart)

This is a good general purpose solution, but for your specific example there's something simpler...

Emoji

Flutter's text supports Emoji out of the box. So you can do this:

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

And you get this:

enter image description here

You can also use Unicode escapes in the string and get the same result:

'Created with \u2764️ by Michael'
like image 123
MichaelM Avatar answered Sep 24 '22 17:09

MichaelM


Regarding Emojis, in android not all emojis are supported (depending on OS version).

For full emoji compatibility you can use the google free font Noto Color Emoji at https://www.google.com/get/noto/#emoji-zsye-color

  • Add it to the fonts folder
  • add in pubspec.yaml
    fonts:
    - family: NotoEmoji
      fonts:
        - asset: fonts/NotoColorEmoji.ttf
          weight: 400
  • use with TextStyle

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

like image 41
Ignacio Tomas Crespo Avatar answered Sep 24 '22 17:09

Ignacio Tomas Crespo