sortARB function
Sorts the .arb formatted String in alphabetical order of the keys.
Sorts the .arb formatted String arbContents in alphabetical order
of the keys, with the @key portion added below it's respective key.
Optionally you can provide a compareFunction for customizing the sorting.
For simplicity sake there are common sorting features you can use when not
defining the former parameter.
Parameters:
arbContents: The ARB file contents as a JSON string to sortcompareFunction: Optional custom comparison function for sorting keyscaseInsensitive: Whether to perform case-insensitive sorting (default: false)naturalOrdering: Whether to use natural ordering (e.g., "2" before "10") (default: false)descendingOrdering: Whether to sort in descending order (default: false)
Returns: Sorted ARB file contents as a JSON string
Example:
final arbContent = '{"zebra": "Zebra", "apple": "Apple", "banana": "Banana"}';
final sorted = sortARB(arbContent);
// Result: '{"apple": "Apple", "banana": "Banana", "zebra": "Zebra"}'
// Case insensitive sorting
final sortedCaseInsensitive = sortARB(arbContent, caseInsensitive: true);
// Natural ordering (useful for numbered keys)
final sortedNatural = sortARB('{"item2": "Item 2", "item10": "Item 10", "item1": "Item 1"}', naturalOrdering: true);
// Result: '{"item1": "Item 1", "item2": "Item 2", "item10": "Item 10"}'
Implementation
String sortARB(String arbContents,
{int Function(String, String)? compareFunction,
bool caseInsensitive = false,
bool naturalOrdering = false,
bool descendingOrdering = false}) {
compareFunction ??= (a, b) =>
_commonSorts(a, b, caseInsensitive, naturalOrdering, descendingOrdering);
final sorted = <String, dynamic>{};
final Map<String, dynamic> contents = json.decode(arbContents);
final keys = contents.keys.where((key) => !key.startsWith('@')).toList()
..sort(compareFunction);
// Add at the beginning the [Global Attributes] of the .arb original file, if any
// [link]: https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#global-attributes
contents.keys.where((key) => key.startsWith('@@')).toList()
..sort(compareFunction)
..forEach((key) {
sorted[key] = contents[key];
});
for (final key in keys) {
sorted[key] = contents[key];
if (contents.containsKey('@$key')) {
sorted['@$key'] = contents['@$key'];
}
}
final encoder = JsonEncoder.withIndent(' ');
return encoder.convert(sorted);
}