Skip to content

Instantly share code, notes, and snippets.

@sajjadjaved01
Last active November 3, 2023 10:37
Show Gist options
  • Save sajjadjaved01/f297c2a138d3661cc150e823cee0089e to your computer and use it in GitHub Desktop.
Save sajjadjaved01/f297c2a138d3661cc150e823cee0089e to your computer and use it in GitHub Desktop.
Extract Strings from Flutter / Dart Project. Also if you are using Easy Localization, you can add one translation at a time to all json files.
import 'dart:io';
import 'dart:convert';
void updateLocalizationKeyInLanguages(
List<String> filePaths, String key, Map<String, String> translations) {
try {
for (String filePath in filePaths) {
File file = File(filePath);
if (file.existsSync()) {
String content = file.readAsStringSync();
Map<String, dynamic> jsonData = json.decode(content);
// Update the value for the specified key with translations for each language.
// print(filePath.split('.').first.split("/")[2]);
jsonData[key] = translations[filePath.split('.').first.split("/")[2]];
String updatedContent = json.encode(jsonData);
file.writeAsStringSync(updatedContent);
print('Updated "$key" in $filePath.');
} else {
print('File not found at $filePath');
}
}
} catch (e) {
print('Error updating JSON files: $e');
}
}
Future<List<String>> loadJsonFilesFromAssets() async {
final Directory directory = Directory("assets/translations");
final List<String> jsonFiles = [];
if (await directory.exists()) {
final List<FileSystemEntity> files = directory.listSync();
for (var file in files) {
if (file is File && file.path.toLowerCase().endsWith('.json')) {
jsonFiles.add(file.path);
}
}
}
return jsonFiles;
}
void main(List<String> arguments) async {
if (arguments.length < 2) {
print('Usage: dart script.dart <keyToUpdate> <jsonDirectory>');
return;
}
String jsonKey = arguments[0];
String keyToUpdate = 'newsletters';
// Translations for the "update" key in different languages.
Map<String, String> translations = {
"en": "Newsletters",
"de": "Newsletter",
"nl": "Nieuwsbrieven",
"es": "Boletines",
"pt": "Boletins informativos",
"ar": "النشرات الإخبارية",
"ru": "Новостные бюллетени",
"es-419": "Boletines"
};
final jsonFilePaths = await loadJsonFilesFromAssets();
if (jsonFilePaths.isNotEmpty) {
updateLocalizationKeyInLanguages(jsonFilePaths, keyToUpdate, translations);
} else {
print('No JSON files found in the specified directory.');
}
}
import 'dart:io';
import 'dart:convert';
void main() {
final extractedStrings = <String, String>{};
// Replace 'lib' with the path to your Flutter project's source code directory.
final projectDirectory = Directory('lib');
_scanDirectory(projectDirectory, extractedStrings);
final sanitizedStrings = <String, String>{};
extractedStrings.forEach((key, value) {
final sanitizedKey = sanitizeKey(key);
sanitizedStrings[sanitizedKey] = value.contains("-") ? value.replaceAll("_", " ") : value;
});
final outputFile = File('strings.json');
outputFile.writeAsStringSync(jsonEncode(extractedStrings), flush: true);
}
String sanitizeKey(String key) {
// Convert to lowercase and replace spaces with underscores.
return key
.replaceAll(RegExp(r'[^a-z0-9]'), '_')
.replaceAll(RegExp(r'^_+|_+$'), '').toLowerCase();
}
void _scanDirectory(Directory directory, Map<String, String> extractedStrings) {
final files = directory.listSync();
for (final file in files) {
if (file is File && file.path.endsWith('.dart')) {
final content = file.readAsStringSync();
final stringLiterals = RegExp(r"'(.*?)'").allMatches(content);
for (final match in stringLiterals) {
final extractedString = match.group(1);
if (extractedString != null &&
!extractedString.contains('package:') &&
!extractedString.contains('dart') &&
!extractedString.startsWith('https') &&
!extractedString.contains('\$') &&
!extractedString.contains('getIt<') &&
!extractedString.contains('AppUrl') &&
!extractedString.contains('/') &&
!extractedString.contains('\\')) {
extractedStrings[extractedString] = extractedString;
}
}
} else if (file is Directory) {
_scanDirectory(file, extractedStrings);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment