detectTextDirection function

TextDirection? detectTextDirection(
  1. String text
)

Detects the paragraph direction of text from its first strong character, following rules P2 and P3 of the Unicode Bidirectional Algorithm (UAX #9).

  • Characters of class L give TextDirection.ltr; R and AL give TextDirection.rtl.
  • Characters between an isolate initiator (LRI, RLI, FSI) and its matching PDI are skipped, as P2 requires.
  • Only the first paragraph is examined (text up to the first paragraph separator: LF, CR, U+001C–U+001E, U+0085, U+2029), matching how a text field applies a single direction.

Returns null when the (first paragraph of the) text has no strong character, e.g. it is empty or contains only digits, spaces, punctuation or emoji.

Implementation

TextDirection? detectTextDirection(String text) {
  var isolateDepth = 0;
  for (final rune in text.runes) {
    if (_isParagraphSeparator(rune)) break;
    if (rune == _lri || rune == _rli || rune == _fsi) {
      isolateDepth++;
      continue;
    }
    if (rune == _pdi) {
      if (isolateDepth > 0) isolateDepth--;
      continue;
    }
    if (isolateDepth > 0) continue;
    final strong = strongDirectionOf(rune);
    if (strong == null) continue;
    return strong == StrongDirection.leftToRight
        ? TextDirection.ltr
        : TextDirection.rtl;
  }
  return null;
}