| 1 | import 'package:flutter/material.dart'; |
| 2 | |
| 3 | Locale? parseLocaleCode(String? localeCode) { |
| 4 | if (localeCode == null) { |
| 5 | return null; |
| 6 | } |
| 7 | |
| 8 | final normalized = localeCode.trim().replaceAll('-', '_'); |
| 9 | if (normalized.isEmpty) { |
| 10 | return null; |
| 11 | } |
| 12 | |
| 13 | final parts = normalized.split('_'); |
| 14 | final languageCode = parts.first.toLowerCase(); |
| 15 | |
| 16 | if (parts.length == 1) { |
| 17 | return Locale(languageCode); |
| 18 | } |
| 19 | |
| 20 | final secondPart = parts[1]; |
| 21 | final scriptCode = secondPart.length == 4 ? secondPart : null; |
| 22 | final countryCode = scriptCode == null ? secondPart.toUpperCase() : null; |
| 23 | final resolvedCountryCode = parts.length > 2 |
| 24 | ? parts[2].toUpperCase() |
| 25 | : countryCode; |
| 26 | |
| 27 | return Locale.fromSubtags( |
| 28 | languageCode: languageCode, |
| 29 | scriptCode: scriptCode, |
| 30 | countryCode: resolvedCountryCode, |
| 31 | ); |
| 32 | } |
| 33 | |
| 34 | Locale? findSupportedLocale( |
| 35 | String? localeCode, |
| 36 | Iterable<Locale> supportedLocales, |
| 37 | ) { |
| 38 | final parsedLocale = parseLocaleCode(localeCode); |
| 39 | if (parsedLocale == null) { |
| 40 | return null; |
| 41 | } |
| 42 | |
| 43 | for (final locale in supportedLocales) { |
| 44 | if (_sameLocale(locale, parsedLocale)) { |
| 45 | return locale; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | for (final locale in supportedLocales) { |
| 50 | if (locale.languageCode == parsedLocale.languageCode) { |
| 51 | return locale; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | return null; |
| 56 | } |
| 57 | |
| 58 | bool _sameLocale(Locale a, Locale b) { |
| 59 | return a.languageCode == b.languageCode && |
| 60 | (a.scriptCode ?? '') == (b.scriptCode ?? '') && |
| 61 | (a.countryCode ?? '') == (b.countryCode ?? ''); |
| 62 | } |