Displaying text with Emojis on Flutter
Asked Answered
B

7

33

I have some texts that contain emojis and I'm trying to show them on the Text widget. However, they seem to be shown as foreign characters. Does Flutter support showing emojis? should work for both iOS and Android

Backstage answered 5/7, 2017 at 21:23 Comment(0)
D
31

The Problem

As of now, unfortunately, Flutter uses the default Emojis supported on a given platform. Therefore, when building a cross-platform app you may face issues of Emojis showing on certain devices and not on others.

The Solution

The solution I settled for is to use a custom Emoji font such as Emoji One and RichText widget instead of the basic Text widget.

With this, you can simply have:

RichText(
  text: TextSpan(
    children: <TextSpan>[
      TextSpan(
        text: 'Hello',  // non-emoji characters
      ),
      TextSpan(
        text: '🧭 🏳️\u200d🌈', // emoji characters
        style: TextStyle(
          fontFamily: 'EmojiOne',
        ),
      ),
    ],
  ),
);

Generalized Solution

With this idea, we can even create a custom widget that given a string, builds a RichText object with all the TextSpans autocreated:

class EmojiText extends StatelessWidget {

  const EmojiText({
    Key key,
    @required this.text,
  }) : assert(text != null),
       super(key: key);

  final String text;

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: _buildText(this.text),
    );
  }

  TextSpan _buildText(String text) {
    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(
            fontFamily: isEmoji ? 'EmojiOne' : null,
          ),
        ),
      );
    }

    return TextSpan(children: children);
  } 
} 

Which can be used as:

EmojiText(text: 'Hello there: 🧭 🏳️\u200d🌈');

This has the advantage of having the consistent support of Emojis on your app that you can control on different platforms.

The downside is that it will add some MBs to your app.

Datura answered 1/7, 2019 at 17:20 Comment(4)
This is the most complete solution to integrate emoji within text in Flutter, tanks ! – Pinckney
Emoji One seems to have become a paid service called JoyPixels. I am considering an open source Apache Licence font of Google with the solution above. Font is called Noto Emoji github.com/googlefonts/noto-emoji – Vaunting
This is so great that you should make a library out of this ! – Acquiesce
Do you have any idea how to do that on a TextField instead of a Text ? – Acquiesce
M
22

You can insert emoji in the text field through following way:

If you're on Mac, you can hit Control + Command + Space. Windows users can hit the "Windows key" + ; (semicolon).

Copy pasted the instruction from @Reso Coder https://www.youtube.com/watch?v=KfuUkq2cLZU&t=15s

I tested on mac and it works.

Musquash answered 11/5, 2020 at 5:1 Comment(2)
I've just post my answer and then I found yours :) – Tomtoma
For me it was actually "win" + "." on windows – Fayth
L
15

Flutter supports emoji. Here's some code that demonstrates emoji text entry. (If you're seeing foreign characters, it's likely that you're decoding bytes as ASCII instead of UTF-8; we can show you how to fix this if you update your question with code that demonstrates the problem.)

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '🐣';

  Future<String> _promptForString(String label, { String hintText }) {
    final TextEditingController controller = new TextEditingController();
    return showDialog(
      context: context,
      child: new AlertDialog(
        title: new Text(label),
        content: new TextFormField(
          controller: controller,
          decoration: new InputDecoration(hintText: hintText),
        ),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('CANCEL'),
          ),
          new FlatButton(
            onPressed: () => Navigator.pop(context, controller.text),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_message),
      ),
      body: new Center(
        child: new Text(_message, style: Theme.of(context).textTheme.display2),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.edit),
        onPressed: () async {
          String message = await _promptForString('New text', hintText: 'Try emoji!');
          if (!mounted)
            return;
          setState(() {
            _message = message;
          });
        },
      ),
    );
  }
}
Lientery answered 5/7, 2017 at 21:57 Comment(5)
Is there a way to show a dedicates Emoji Screen in Flutter? I dont mean the Emojis integrated in the Keyboard. – Leibowitz
@colin-jackson flag emoji's on iOS are not working using your code above. All other emoji's work. I need the flag emoji's for a flutter app I'm building. Any idea's? Is this a unicode/utf-8 decode problem? – Expanded
Looks like a bug was filed for this: github.com/flutter/flutter/issues/16960. Thumbs up on the bug to help prioritize :) – Expanded
BTW: As a workaround for use cases that don't involve keyboard input it might be useful to use pub.dartlang.org/packages/country_icons – Expanded
Where can I get these whatsapp like emojis ? – Trisect
M
13

If you just want to include emoji in Text widget, you can copy emoji from somewhere else and paste it inside the text widget. I use GeteMoji to copy emojis.

See the Output Screenshot

CODE : See 8th Row.

Widget build(BuildContext context) {
    return Center(
        child: Container(
            alignment: Alignment.center,
            color: Colors.deepPurple,
            //width: 200.0,
            //height: 100.0,
            child: Text("Emoji 🀣 ",
                style: TextStyle(
                  fontFamily: 'Raleway',
                  fontSize: 40,
                  decoration: TextDecoration.none,
                  color: Colors.white

                ))));
  }
Mekong answered 30/12, 2018 at 8:25 Comment(0)
D
9

For full emoji compatibility (at least in android, not all emojis are supported in old OS versions) 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'))

Dragon answered 4/11, 2019 at 11:33 Comment(4)
Does this work in the latest flutter and ios sim? With ios13.2 on iPhone 8 simulator I get a crash with this message: [VERBOSE-2:FontFamily.cpp(184)] Could not get cmap table size! [VERBOSE-3:FontCollection.cpp(95)] nTypefaces == 0 – Sean
I see that font is not compatible with iOS or MacOS and since Apple won't let us use their emojis as sprites in games I need to find another nice emoji font. – Sean
@lostbaby Really? Can you to a reference for that? – Orlosky
@Ignacio - unfortunatly NotoEmoji doesn't support plain text and render spaces incorrectly. – Orlosky
I
2

When an emoji is not showing up, the issue is most likely the font you are using.

Before trying out an emoji font package, you can give the text field an empty string as fontFamily or try out the default font options packaged with flutter. This will prevent adding dependencies that are not needed.

for example this emoji was not showing on android with 'Product Sans' as fontFamily, i simply added an empty string and font family for the text field, and that fixed the issue.

Text('₦', TextStyle(fontFamily: ''))
Intertidal answered 17/7, 2020 at 12:16 Comment(0)
B
0

You can easily use the fontFamily as a style to solve the problem I used it with the package

auto_size_text: ^2.1.0

AutoSizeText(
              lesson.FullExercise,
              textAlign: TextAlign.justify,
              style:TextStyle(
              fontFamily: 'EmojiOne',
              ),
            ),

Good note to mention If you want to store data in MySQL and the text contains Emojis you need to change the collection of the text to utf8mb4

Beniamino answered 22/8, 2021 at 21:19 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.