Skip to content

Locale Detection

Kenny Mochizuki Escalona edited this page Aug 16, 2026 · 1 revision

Locale Detection

Detecting System Locale

LayrzI18n.detectedLocale returns the system's current locale as a Locale:

final detected = LayrzI18n.detectedLocale;
// e.g., Locale('en', 'US') on an English US device

This is useful for automatically selecting the user's preferred language when your app starts.

Finding the Closest Match

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'),
);

Fallback Ladder

getClosestLocale() applies this priority order:

  1. Exact match: If prevLanguage exactly matches a supported locale (e.g., 'en' matches Locale('en') or 'en-US' matches Locale('en', 'US'))
  2. Language-code match: If the language code of prevLanguage matches a supported locale (e.g., 'en-GB' language code 'en' matches Locale('en', 'US'))
  3. Detected match: If the detected system locale exactly matches a supported locale
  4. Detected language match: If the language code of the detected locale matches a supported locale
  5. Fallback: The fallbackLocale parameter (e.g., Locale('en'))

Parsing Locale Strings

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)

Implementation Details

  • 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')

Clone this wiki locally