Created
September 1, 2020 09:26
-
-
Save ruan65/63e14189b94dda4a6e31473790cde63a to your computer and use it in GitHub Desktop.
localization example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
const appSupportedLocales = <Locale>[ | |
Locale('ru'), | |
Locale('en'), | |
]; | |
class AppLocalisationDelegate extends LocalizationsDelegate<AppLocalizations> { | |
@override | |
bool isSupported(Locale locale) { | |
return appSupportedLocales.contains(locale); | |
} | |
@override | |
bool shouldReload(LocalizationsDelegate old) { | |
return false; | |
} | |
@override | |
Future<AppLocalizations> load(Locale locale) async { | |
final appLocalisation = AppLocalizations(locale); | |
await appLocalisation.load(); | |
return appLocalisation; | |
} | |
} | |
class AppLocalizations { | |
final Locale locale; | |
Map keys; | |
AppLocalizations(this.locale); | |
Map<String, String> flatten(Map map, {String prefix}) { | |
final output = Map<String, String>(); | |
map.forEach((key, value) { | |
final keyWithPrefix = prefix != null ? '$prefix.$key' : key; | |
if (value is Map) { | |
output.addAll(flatten(value, prefix: keyWithPrefix)); | |
} else { | |
output[keyWithPrefix] = value; | |
} | |
}); | |
return output; | |
} | |
Future load() async { | |
final data = | |
await rootBundle.loadString('assets/i18n/${locale.languageCode}.json'); | |
final dataDecoded = json.decode(data); | |
keys = flatten(dataDecoded); | |
} | |
static AppLocalizations of(BuildContext context) { | |
return Localizations.of<AppLocalizations>(context, AppLocalizations); | |
} | |
String translate(String key) { | |
final text = keys[key]; | |
return text != null ? text : key; | |
} | |
} | |
String translate(BuildContext context, key) => | |
Localizations.of<AppLocalizations>(context, AppLocalizations) | |
.translate(key); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment