firstLocaleTag function
Parses the first valid BCP-47 language tag from an Accept-Language header string.
Extracts the leading entry from header, ignoring wildcard tokens ("*") and
discarding quality weighting parameters (";q=..."). Returns null if header is
empty or contains no valid language tag.
final tag = firstLocaleTag('fr-CH, fr;q=0.9, en;q=0.8');
// tag: "fr-CH"
See also:
- parseAcceptLanguage, for parsing and sorting all entries in a header.
- resolveLocale, for matching candidate tags against supported catalogs.
Implementation
String? firstLocaleTag(String? header) {
if (header == null) return null;
final firstPart = header.split(',').firstOrNull;
if (firstPart == null) return null;
final tag = firstPart.trim().split(';').firstOrNull?.trim();
if (tag == null || tag.isEmpty || tag == '*') {
return null;
}
return _isValidLanguageTag(tag) ? tag : null;
}