-
Notifications
You must be signed in to change notification settings - Fork 0
Locale Detection
Kenny Mochizuki Escalona edited this page Aug 16, 2026
·
1 revision
LayrzI18n.detectedLocale returns the system's current locale as a Locale:
final detected = LayrzI18n.detectedLocale;
// e.g., Locale('en', 'US') on an English US deviceThis is useful for automatically selecting the user's preferred language when your app starts.
Use LayrzI18n.getClosestLocale() to select a supported locale based on the user's preference, detected system locale, and a fallback.
final locale = LayrzI18n.getClosestLocale(
prevLanguage: savedLanguageCode, // e.g., 'en' (optional)
supportedLocales: supportedLocales, // List of Locale
fallbackLocale: const Locale('en'),
);getClosestLocale() applies this priority order:
-
Exact match: If
prevLanguageexactly matches a supported locale (e.g.,'en'matchesLocale('en')or'en-US'matchesLocale('en', 'US')) -
Language-code match: If the language code of
prevLanguagematches a supported locale (e.g.,'en-GB'language code'en'matchesLocale('en', 'US')) - Detected match: If the detected system locale exactly matches a supported locale
- Detected language match: If the language code of the detected locale matches a supported locale
-
Fallback: The
fallbackLocaleparameter (e.g.,Locale('en'))
The parseLocale() function converts a string locale code into a Dart Locale object. It handles multiple formats:
parseLocale('en') // Locale('en')
parseLocale('en-US') // Locale('en', 'US')
parseLocale('en_US') // Locale('en', 'US') (underscore normalized)
parseLocale('en-') // Locale('en') (malformed codes fixed)
parseLocale('zh-Hans-CN') // Locale('zh', 'Hans') (second segment as region)
parseLocale('') // Locale('en') (empty defaults to English)
parseLocale(null) // Locale('en') (null defaults to English)- Hyphens and underscores are treated identically
- The first part is the language code
- The second part (if non-empty) is the region code
- Any parts after the second are ignored
- Empty or null input returns
Locale('en')
Made with ❤️ by Golden M, Inc.