Skip to content

Instantly share code, notes, and snippets.

@hyochan
Last active April 15, 2020 16:34
Show Gist options
  • Save hyochan/7dce34518339f7935697484a68092072 to your computer and use it in GitHub Desktop.
Save hyochan/7dce34518339f7935697484a68092072 to your computer and use it in GitHub Desktop.
flutter_localized_example/localization.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class Localization {
Localization(this._locale, {
this.isTest = false,
});
final Locale _locale;
bool isTest;
Map<String, String> _sentences;
static Localization of(BuildContext context) {
return Localizations.of<Localization>(context, Localization);
}
Future<Localization> loadTest(Locale locale) async {
return Localization(locale);
}
Future<Localization> load() async {
String data = await rootBundle
.loadString('res/langs/${_locale.languageCode}.json');
Map<String, dynamic> _result = json.decode(data);
_sentences = new Map();
_result.forEach((String key, dynamic value) {
_sentences[key] = value.toString();
});
return Localization(_locale);
}
String trans(String key) {
if (isTest) return key;
if (key == null) {
return '...';
}
return _sentences[key];
}
}
class LocalizationDelegate extends LocalizationsDelegate<Localization> {
const LocalizationDelegate({
this.isTest = false,
});
final bool isTest;
@override
bool isSupported(Locale locale) => ['en', 'ko'].contains(locale.languageCode);
@override
Future<Localization> load(Locale locale) async {
Localization localizations = new Localization(locale, isTest: isTest);
if (isTest) {
await localizations.loadTest(locale);
} else {
await localizations.load();
}
return localizations;
}
@override
bool shouldReload(LocalizationDelegate old) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment