-
Notifications
You must be signed in to change notification settings - Fork 0
/
locale_cubit.dart
63 lines (53 loc) · 1.83 KB
/
locale_cubit.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:myapp/settings/settings.dart';
import 'package:repositories/repositories.dart';
class LocaleCubit extends Cubit<AppLocale> {
LocaleCubit({required LocalPersistence localePersistence})
: _localePersistence = localePersistence,
// start with the system lang from the device
super(systemLocale) {
_getInitLocale();
}
final LocalPersistence _localePersistence;
static final systemLocale = AppLocale(
key: 'system',
desc: 'systemLanuage',
locale: WidgetsBinding.instance.platformDispatcher.locale);
// for the desc, dont forget to add the key-code of the language as desc in app_*.arb files
// so far only de and en are added
static final Map<String, AppLocale> locales = {
'system': systemLocale,
for (var locale in AppLocalizations.supportedLocales)
locale.languageCode.substring(0, 2): AppLocale(
key: locale.languageCode.substring(0, 2),
desc: locale.languageCode.substring(0, 2),
locale: locale)
};
Map<String, AppLocale> getLocales() => locales;
_getInitLocale() async {
final initLocale = await _localePersistence.getLocale();
if (!_isValidLocale(initLocale)) {
return;
}
if (initLocale == 'system') {
emit(systemLocale);
} else {
final locale = Locale(initLocale);
emit(
AppLocale(
key: locale.languageCode.substring(0, 2),
desc: locale.languageCode.substring(0, 2),
locale: locale),
);
}
}
changeLocale(AppLocale appLocale) {
emit(appLocale);
_localePersistence.saveLocale(appLocale.key);
}
bool _isValidLocale(String localeKey) {
return (localeKey.isNotEmpty);
}
}