66 lines
1.8 KiB
Dart
66 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
|
|
import 'package:get/get.dart';
|
|
import 'package:encrypt_shared_preferences/provider.dart';
|
|
|
|
class MyTranslations extends Translations {
|
|
static final MyTranslations instance = MyTranslations._internal();
|
|
MyTranslations._internal();
|
|
|
|
static final Map<String, Map<String, String>> _translations = {};
|
|
|
|
static Future<void> loadTranslations() async {
|
|
final locales = ['en_US', 'de_DE', 'fr_FR', 'nl_NL'];
|
|
for (final locale in locales) {
|
|
final String jsonString = await rootBundle.loadString(
|
|
'assets/i18n/$locale.json',
|
|
);
|
|
final Map<String, dynamic> jsonMap = json.decode(jsonString);
|
|
_translations[locale] = jsonMap.map(
|
|
(key, value) => MapEntry(key, value.toString()),
|
|
);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Map<String, Map<String, String>> get keys => _translations;
|
|
}
|
|
|
|
class LocalizationController extends GetxController {
|
|
final EncryptedSharedPreferencesAsync storage =
|
|
EncryptedSharedPreferencesAsync.getInstance();
|
|
Rx<Locale> currentLocale = const Locale('en', 'US').obs;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
loadLocale();
|
|
}
|
|
|
|
Future<void> loadLocale() async {
|
|
String? savedLocale = await storage.getString(
|
|
'locale',
|
|
defaultValue: 'en_US',
|
|
);
|
|
if (savedLocale != null && savedLocale.isNotEmpty) {
|
|
final List<String> parts = savedLocale.split('_');
|
|
currentLocale.value = parts.length == 2
|
|
? Locale(parts[0], parts[1])
|
|
: Locale(parts[0]);
|
|
Get.locale = currentLocale.value;
|
|
}
|
|
}
|
|
|
|
Future<void> changeLocale(Locale newLocale) async {
|
|
currentLocale.value = newLocale;
|
|
Get.updateLocale(newLocale);
|
|
await storage.setString(
|
|
'locale',
|
|
'${newLocale.languageCode}_${newLocale.countryCode}',
|
|
);
|
|
}
|
|
}
|