Created
January 11, 2022 02:32
-
-
Save Jay-flow/6c43811f8bffe1473e26f2478f7877f9 to your computer and use it in GitHub Desktop.
Flutter custom 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:async'; | |
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
class Localization { | |
Localization(this.locale); | |
final Locale locale; | |
static Localization of(BuildContext context) { | |
return Localizations.of<Localization>(context, Localization); | |
} | |
Map<String, dynamic> _sentences; | |
Future<bool> load() async { | |
print('languageCode: ${this.locale.languageCode}'); | |
String data = await rootBundle.loadString('res/langs/${this.locale.languageCode}.json'); | |
print('$data'); | |
this._sentences = json.decode(data); | |
return true; | |
} | |
String trans(String key) { | |
if (key == null) { | |
return '...'; | |
} | |
return this._sentences[key]; | |
} | |
} | |
class LocalizationDelegate extends LocalizationsDelegate<Localization> { | |
const LocalizationDelegate(); | |
@override | |
bool isSupported(Locale locale) => ['en', 'ko'].contains(locale.languageCode); | |
@override | |
Future<Localization> load(Locale locale) async { | |
print("locale: $locale"); | |
Localization localizations = new Localization(locale); | |
await localizations.load(); | |
print("Load ${locale.languageCode}"); | |
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