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:app_finance/l10n/app_localization.dart';
7 : import 'package:app_finance/l10n/app_localization_en.dart';
8 : import 'package:material_ui/material_ui.dart';
9 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
10 :
11 : class AppLocale extends ValueNotifier<Locale?> {
12 : static String code = 'en';
13 6 : static AppLocalizations labels = AppLocalizationsEn();
14 :
15 18 : AppLocale() : super(_initialLocale());
16 :
17 6 : static Locale? _initialLocale() {
18 6 : final prefCode = AppPreferences.get(AppPreferences.prefLocale);
19 6 : if (prefCode != null && prefCode.isNotEmpty) {
20 : code = prefCode;
21 : }
22 6 : return AppLocale.fromCode(code);
23 : }
24 :
25 6 : static Locale? fromCode(String value) {
26 : try {
27 6 : final keys = value.split('_');
28 24 : return Locale.fromSubtags(languageCode: keys.first, countryCode: keys.length > 1 ? keys.last : null);
29 : } catch (e) {
30 : return null;
31 : }
32 : }
33 :
34 0 : static Locale get() => AppLocale.fromCode(AppPreferences.get(AppPreferences.prefLocale) ?? '') ?? Locale('en', 'US');
35 :
36 6 : Future<void> set(String newValue, [Function? callback]) async {
37 6 : final loc = fromCode(newValue);
38 12 : if (loc != null && loc != value && AppLocalizations.supportedLocales.contains(loc)) {
39 0 : value = loc;
40 0 : code = value.toString();
41 0 : await AppPreferences.set(AppPreferences.prefLocale, newValue);
42 : CurrencyDefaults.defaultLocale = loc;
43 : if (callback != null) {
44 0 : callback();
45 : }
46 0 : notifyListeners();
47 : }
48 : }
49 :
50 6 : void updateState(BuildContext context) {
51 12 : final value = Localizations.localeOf(context).toString();
52 6 : labels = AppLocalizations.of(context) ?? AppLocalizationsEn();
53 12 : CurrencyProvider.initFromContext(context, locale: super.value);
54 6 : if (AppPreferences.get(AppPreferences.prefDesign) == null) {
55 18 : AppPreferences.set(AppPreferences.prefDesign, AppDesign.fromLocale(fromCode(value)));
56 : }
57 6 : set(value);
58 : }
59 : }
|