Line data Source code
1 : // Copyright 2023 The terCAD team. All rights reserved. 2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file. 3 : 4 : import 'package:app_finance/_classes/herald/app_design.dart'; 5 : import 'package:app_finance/_classes/storage/app_preferences.dart'; 6 : import 'package:flutter/material.dart'; 7 : import 'package:flutter_currency_picker/flutter_currency_picker.dart'; 8 : import 'package:flutter_gen/gen_l10n/app_localization.dart'; 9 : import 'package:flutter_gen/gen_l10n/app_localization_en.dart'; 10 : 11 : class AppLocale extends ValueNotifier<Locale?> { 12 12 : static String code = AppPreferences.get(AppPreferences.prefLocale) ?? 'en'; 13 3 : static AppLocalizations labels = AppLocalizationsEn(); 14 : 15 12 : AppLocale() : super(AppLocale.fromCode(code)); 16 : 17 3 : static Locale? fromCode(String value) { 18 : try { 19 3 : final keys = value.split('_'); 20 12 : return Locale.fromSubtags(languageCode: keys.first, countryCode: keys.length > 1 ? keys.last : null); 21 : } catch (e) { 22 : return null; 23 : } 24 : } 25 : 26 3 : Future<void> set(String newValue, [Function? callback]) async { 27 3 : final loc = fromCode(newValue); 28 6 : if (loc != null && loc != value && AppLocalizations.supportedLocales.contains(loc)) { 29 0 : value = loc; 30 0 : code = value.toString(); 31 0 : await AppPreferences.set(AppPreferences.prefLocale, newValue); 32 : CurrencyDefaults.defaultLocale = loc; 33 : if (callback != null) { 34 0 : callback(); 35 : } 36 0 : notifyListeners(); 37 : } 38 : } 39 : 40 3 : void updateState(BuildContext context) { 41 6 : final value = Localizations.localeOf(context).toString(); 42 3 : labels = AppLocalizations.of(context) ?? AppLocalizationsEn(); 43 6 : CurrencyProvider.initFromContext(context, locale: super.value); 44 3 : if (AppPreferences.get(AppPreferences.prefDesign) == null) { 45 9 : AppPreferences.set(AppPreferences.prefDesign, AppDesign.fromLocale(fromCode(value))); 46 : } 47 3 : set(value); 48 : } 49 : }