Skip to content

Instantly share code, notes, and snippets.

@MoshDev
Last active June 19, 2022 11:15
Show Gist options
  • Save MoshDev/817b04ad52b161fa1b064b5b69e27f85 to your computer and use it in GitHub Desktop.
Save MoshDev/817b04ad52b161fa1b064b5b69e27f85 to your computer and use it in GitHub Desktop.
Future main() async {
final Iterable<Locale> supportedLocales = [Locale('en'), Locale('ar')];
await Langs.init(supportedLocales: supportedLocales, loadDeviceLanguage: true);
runApp(MyApp(supportedLocales: supportedLocales));
print(Langs.string('sample.item.name'));
print(Langs.string('name'));
}
{
"name": "Hello World!",
"sample": {
"item": {
"name": "Hello Nested World!"
}
}
}
import 'dart:convert';
import 'dart:ui';
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart' show rootBundle;
class Langs {
static Map<String, dynamic> _currentLanguage;
static Iterable<Locale> _supportedLocales;
static Locale _defaultLocale;
static Future init(
{Locale defaultLocale = const Locale('en'),
Iterable<Locale> supportedLocales = const [Locale('en')],
bool loadDeviceLanguage = false}) async {
_defaultLocale = defaultLocale;
_supportedLocales = supportedLocales;
if (loadDeviceLanguage) {
await Langs.loadDeviceLanguage();
}
}
static Future loadDeviceLanguage() async {
final deviceLocale = ui.window.locale;
if (_supportedLocales.contains(deviceLocale)) {
await setLang(deviceLocale.toLanguageTag());
} else {
if (_supportedLocales
.map((l) => l.languageCode)
.contains(deviceLocale.languageCode)) {
await setLang(deviceLocale.languageCode);
} else {
await setLang(_defaultLocale.toLanguageTag());
}
}
}
static Future setLang(String lang) async {
_currentLanguage =
json.decode(await rootBundle.loadString("resources/langs/$lang.json"));
}
static string(String id) {
if (id.contains('.')) {
return id.split('.').fold(_currentLanguage, (map, key) {
return map[key];
});
} else {
if (_currentLanguage.containsKey(id)) {
return _currentLanguage[id];
}
throw Exception("No translation found for key: $id");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment