buildTextSpan method

  1. @override
TextSpan buildTextSpan({
  1. required BuildContext context,
  2. required bool withComposing,
  3. TextStyle? style,
})
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,
  required bool withComposing,
  TextStyle? style,
}) {
  final children = <InlineSpan>[];
  Patterns? patternMatched;
  String? formatText;
  TextStyle? myStyle;

  text.splitMapJoin(
    pattern,
    onMatch: (Match match) {
      myStyle = patterns[match[0]] ??
          patterns[patterns.keys.firstWhere(
            (e) {
              var ret = false;
              RegExp(e, multiLine: true).allMatches(text).forEach((element) {
                if (element.group(0) == match[0]) {
                  patternMatched =
                      Patterns.values.firstWhere((s) => s.pattern == e);
                  ret = true;
                  return;
                }
              });
              return ret;
            },
          )];

      if (patternMatched == null) {
        return '';
      }

      switch (patternMatched!) {
        case Patterns.BOLD_TEXT_PATTERN:
          formatText = match[0];
        case Patterns.CHECKBOX_LIST_PATTERN:
          formatText = match[0]?.replaceAll('- [ ]', '   ☐ ');
        case Patterns.CHECKBOX_LIST_DONE_PATTERN:
          formatText = match[0]?.replaceAll('- [x]', '   ☑ ');
        case Patterns.CODE_PATTERN:
          formatText = match[0];
        case Patterns.URL_PATTERN:
          formatText = match[0];
        case Patterns.HEADERS_PATTERN:
          formatText = match[2];
      }

      children.addAll([
        if (match.groupCount > 0)
          TextSpan(
            text: match[1],
            style: myStyle?.merge(
              const TextStyle(
                fontWeight: FontWeight.normal,
                color: Colors.grey,
              ),
            ),
          ),
        TextSpan(
          text: formatText,
          style: style?.merge(myStyle),
          recognizer: _checkboxTapRecognizer(match[0], patternMatched),
        ),
      ]);
      return '';
    },
    onNonMatch: (String text) {
      children.add(TextSpan(text: text, style: style));
      return '';
    },
  );

  return TextSpan(style: style, children: children);
}