getTextDirection static method
Determines the primary text direction for a given text Returns TextDirection.rtl if the text is primarily RTL, otherwise TextDirection.ltr
Implementation
static TextDirection getTextDirection(String text) {
if (text.isEmpty) return TextDirection.ltr;
int rtlCount = 0;
int ltrCount = 0;
for (int i = 0; i < text.length; i++) {
int codeUnit = text.codeUnitAt(i);
// Check for RTL characters
bool isRTL = false;
for (List<int> range in rtlUnicodeRanges) {
if (codeUnit >= range[0] && codeUnit <= range[1]) {
rtlCount++;
isRTL = true;
break;
}
}
// Check for LTR characters (Latin, numbers, etc.)
if (!isRTL &&
((codeUnit >= 0x0041 && codeUnit <= 0x005A) || // A-Z
(codeUnit >= 0x0061 && codeUnit <= 0x007A) || // a-z
(codeUnit >= 0x0030 && codeUnit <= 0x0039) || // 0-9
(codeUnit >= 0x00C0 && codeUnit <= 0x00FF))) {
// Latin-1 Supplement
ltrCount++;
}
}
// If more than 30% of characters are RTL, consider the text RTL
double rtlRatio = rtlCount / (rtlCount + ltrCount);
return rtlRatio > 0.3 ? TextDirection.rtl : TextDirection.ltr;
}