Localization support for multi-module / package project #592
Unanswered
luckyhandler
asked this question in
Q&A
Replies: 2 comments
-
I have faced the same issue @luckyhandler, here is your answer: First of all, we need to define a class MultiTranslationAssetLoader extends AssetLoader {
const MultiTranslationAssetLoader(this.loaders);
final List<dynamic> loaders;
@override
Future<Map<String, dynamic>> load(String path, Locale locale) async {
final result = <String, dynamic>{};
final loaderFutures = <Future<Map<String, dynamic>?>>[];
for (final loader in loaders) {
loaderFutures.add(loader.load(path, locale));
}
(await Future.wait(loaderFutures))
.whereNotNull()
.forEach(result.addAllRecursive);
return result;
}
}
extension _MapExtension<K> on Map<K, dynamic> {
void addAllRecursive(Map<K, dynamic> other) {
for (final entry in other.entries) {
final oldValue = this[entry.key];
final newValue = entry.value;
if (oldValue is Map<K, dynamic> && newValue is Map<K, dynamic>) {
oldValue.addAllRecursive(newValue);
continue;
}
this[entry.key] = newValue;
}
}
} Then we can use it as follows: runApp(
EasyLocalization(
supportedLocales: const <Locale>[
Locale('en'),
],
fallbackLocale: const Locale('en'),
assetLoader: const MultiTranslationAssetLoader(
[
TranslationsLoader(),
TranslationsLoader(packageName: 'package_example'),
],
),
path: 'lib/l10n/translations',
child: const MainApp(),
),
); Here is a sample implementation of class TranslationsLoader extends AssetLoader {
const TranslationsLoader({this.packageName});
final String? packageName;
@override
Future<Map<String, dynamic>?> load(String path, Locale locale) =>
_getMapLocales(locale);
Future<Map<String, dynamic>> _getMapLocales(Locale locale) async {
String getPath({Locale locale = const Locale('en')}) =>
'${packageName != null ? 'packages/$packageName/' : ''}lib/l10n/translations/$locale.json';
try {
return jsonDecode(await rootBundle.loadString(getPath(locale: locale)));
} catch (e) {
return jsonDecode(await rootBundle.loadString(getPath()));
}
}
} PR #654 Stackoverflow thread: This article helped me to solve this problem: |
Beta Was this translation helpful? Give feedback.
0 replies
-
PR #654 has been merged and adding multiple |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
My app follows a feature-based approach
in the main app I initialize
EasyLocalization
as describedHow can I now localize strings in my packages?
I would like to keep different
json
files in the package so that it is completely autonomous of the main app.Or if this is not possible at least read multiple json files in the main app.
I only found the option to set one file path
-->
path: 'assets/langs',
So how can I achieve this? Any ideas?
Beta Was this translation helpful? Give feedback.
All reactions