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}) {
  // It is very unlikely that the OTP code will contain grapheme clusters but there's no harm being calamitous.
  final characters = text.characters;
  final variants = FOtpFieldScope.of(context).variants;

  final spans = <InlineSpan>[];
  int item = 0;
  for (final (i, child) in children.indexed) {
    if (child is FOtpItemMixin) {
      final character = characters.elementAtOrNull(item);
      spans.add(
        WidgetSpan(
          alignment: .middle,
          child: FOtpItemScope(
            character: character,
            focused: switch (selection) {
              _ when !variants.contains(FTextFieldVariant.focused) => false,
              final s when s.isCollapsed => _focused == item,
              final s => s.start <= item && item < s.end,
            },
            start: i == 0 || children[i - 1] is! FOtpItemMixin,
            end: i == children.length - 1 || children[i + 1] is! FOtpItemMixin,
            child: child,
          ),
        ),
      );
      item++;
      continue;
    }

    spans.add(WidgetSpan(alignment: .middle, child: child));
  }

  return TextSpan(children: Directionality.of(context) == .ltr ? spans : spans.reversed.toList());
}