detectLanguage function
Detects the dominant language of text; returns null when too short.
Heuristic, best-effort only: it compares the input's ranked trigrams against
tiny built-in profiles using an out-of-place rank distance, so short or mixed
text and unsupported languages can mis-detect. Returns null when fewer than
_kMinTrigrams trigrams exist, since there is too little signal to decide.
Example:
detectLanguage('the quick brown fox and the lazy dog')?.language; // 'en'
Audited: 2026-06-12 11:26 EDT
Implementation
LanguageGuess? detectLanguage(String text) {
final List<String> grams = languageTrigrams(text);
if (grams.length < _kMinTrigrams) return null;
// Score every profile and keep the smallest normalized distance. Using
// firstOrNull-style folding avoids any bare .first on a possibly-empty list.
LanguageGuess? best;
for (final MapEntry<String, List<String>> entry in _kProfiles.entries) {
final double score = _profileDistance(grams, entry.value);
if (best == null || score < best.score) {
best = LanguageGuess(entry.key, score);
}
}
return best;
}