buildTextSpan method

  1. @override
TextSpan buildTextSpan({
  1. required BuildContext context,
  2. TextStyle? style,
  3. required bool withComposing,
})
override

Builds TextSpan from current editing value.

By default makes text in composing range appear as underlined. Descendants can override this method to customize appearance of text.

Implementation

@override
TextSpan buildTextSpan(
    {required BuildContext context,
    TextStyle? style,
    required bool withComposing}) {
  int firstIndex = 0;
  includeEmojis.clear();
  do {
    firstIndex = text.indexOf('[', firstIndex);
    if (firstIndex != -1 && text.isNotEmpty) {
      final secondIndex = text.indexOf(']', firstIndex);
      if (secondIndex != -1) {
        String subTxt = text.substring(firstIndex, secondIndex + 1);
        if (EmojiMapping.emojis.contains(subTxt)) {
          includeEmojis.add(EmojiIndex(
            index: firstIndex,
            length: subTxt.length,
            emoji: subTxt,
          ));
        }
      } else {
        break;
      }
      firstIndex = secondIndex + 1;
    }
  } while (firstIndex != -1);

  List<InlineSpan> tp = [];

  if (includeEmojis.isNotEmpty) {
    int index = 0;
    for (var item in includeEmojis) {
      if (item.index > index) {
        tp.add(TextSpan(
          text: text.substring(index, item.index),
          style: style,
        ));
      }
      tp.add(
        WidgetSpan(
          child: ChatImageLoader.emoji(item.emoji, size: 20),
        ),
      );
      index = item.index + item.length;
    }
    if (index < text.length) {
      tp.add(TextSpan(
        text: text.substring(index, text.length),
        style: style,
      ));
    }
  } else {
    tp.add(TextSpan(
      text: text,
      style: style,
    ));
  }

  return TextSpan(children: tp);
}