Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fallback locale for csv asset loader #44

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions lib/src/csv_asset_loader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import 'asset_loader.dart';
//
class CsvAssetLoader extends AssetLoader {
CSVParser? csvParser;
final Locale? fallbackLocale;

CsvAssetLoader([this.fallbackLocale]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer optional args over this:

CsvAssetLoader({this.fallbackLocale});


@override
Future<Map<String, dynamic>> load(String path, Locale locale) async {
Expand All @@ -21,7 +24,7 @@ class CsvAssetLoader extends AssetLoader {
} else {
log('easy localization loader: CSV parser already loaded, read cache');
}
return csvParser!.getLanguageMap(locale.toString());
return csvParser!.getLanguageMap(locale.toString(), fallbackLocale?.toString());
}
}

Expand All @@ -39,6 +42,7 @@ class CSVParser {
final List<List<dynamic>> lines;
final String? fieldDelimiter;
final String? eol;

/// Enables automatic detection of the following
///
/// [eols]: '\r\n' '\n'
Expand Down Expand Up @@ -70,12 +74,19 @@ class CSVParser {
return lines.first.sublist(1, lines.first.length);
}

Map<String, dynamic> getLanguageMap(String localeName) {
Map<String, dynamic> getLanguageMap(
String localeName, [String? fallbackLocale]) {
final indexLocale = lines.first.indexOf(localeName);
final indexFallbackLocale =
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nullable instead of -1

fallbackLocale != null ? lines.first.indexOf(fallbackLocale) : -1;

var translations = <String, dynamic>{};
for (var i = 1; i < lines.length; i++) {
translations.addAll({lines[i][0]: lines[i][indexLocale]});
String localeValue = lines[i][indexLocale];
if (localeValue.isEmpty && indexFallbackLocale != -1) {
localeValue = lines[i][indexFallbackLocale];
}
translations.addAll({lines[i][0]: localeValue});
}
return translations;
}
Expand Down