Skip to content

Instantly share code, notes, and snippets.

@nombrekeff
Created March 27, 2020 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nombrekeff/42ccc698b8799be6b82daae9109d987f to your computer and use it in GitHub Desktop.
Save nombrekeff/42ccc698b8799be6b82daae9109d987f to your computer and use it in GitHub Desktop.
A couple of classes for managing Translations in flutter, from json, with interpolation.
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
class AppLocalizations {
final Locale locale;
AppLocalizations(this.locale);
// Helper method to keep the code in the widgets concise
// Localizations are accessed using an InheritedWidget "of" syntax
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
// Static member to have a simple access to the delegate from the MaterialApp
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
Map<String, String> _localizedStrings;
void setLocalizedStrings(Map<String, String> map) {
this._localizedStrings = map;
}
Future<bool> load() async {
// Load the language JSON file from the "lang" folder
String jsonPath = 'i18n/${locale.languageCode}.json';
String jsonString = await rootBundle.loadString(jsonPath);
print('AppLocalizations::load jsonPath: ' + jsonPath);
Map<String, dynamic> jsonMap = json.decode(jsonString);
_localizedStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
return true;
}
/**
* Translate string, accepts interpolations params
*/
String translate(String key, {Map<String, dynamic> params = const {}}) {
var keys = params.keys;
String result = (_localizedStrings[key] ?? key);
for (var key in keys) {
result = result.replaceAll('{{$key}}', params[key]);
}
return result;
}
}
class _AppLocalizationsDelegate
extends LocalizationsDelegate<AppLocalizations> {
// This delegate instance will never change (it doesn't even have fields!)
// It can provide a constant constructor.
const _AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
// Add your supported variables
var isSupported = ['en'].contains(locale.languageCode);
return isSupported;
}
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations localizations = AppLocalizations(locale);
await localizations.load();
return localizations;
}
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment