Skip to content

Instantly share code, notes, and snippets.

@podcoder
Created April 1, 2020 08:14
Show Gist options
  • Save podcoder/10c16671bdbbef6336d74b11eb89244e to your computer and use it in GitHub Desktop.
Save podcoder/10c16671bdbbef6336d74b11eb89244e to your computer and use it in GitHub Desktop.
Demo localization class and Delegate
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class DemoLocalization {
DemoLocalization(this.locale);
final Locale locale;
static DemoLocalization of(BuildContext context) {
return Localizations.of<DemoLocalization>(context, DemoLocalization);
}
Map<String, String> _localizedValues;
Future<void> load() async {
String jsonStringValues =
await rootBundle.loadString('lib/lang/${locale.languageCode}.json');
Map<String, dynamic> mappedJson = json.decode(jsonStringValues);
_localizedValues =
mappedJson.map((key, value) => MapEntry(key, value.toString()));
}
String translate(String key) {
return _localizedValues[key];
}
// static member to have simple access to the delegate from Material App
static const LocalizationsDelegate<DemoLocalization> delegate =
_DemoLocalizationsDelegate();
}
class _DemoLocalizationsDelegate
extends LocalizationsDelegate<DemoLocalization> {
const _DemoLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'fa', 'ar', 'hi'].contains(locale.languageCode);
}
@override
Future<DemoLocalization> load(Locale locale) async {
DemoLocalization localization = new DemoLocalization(locale);
await localization.load();
return localization;
}
@override
bool shouldReload(LocalizationsDelegate<DemoLocalization> old) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment