I'd like to sort a list of countries in Dart, by localised country name. This is how I'm doing it:
final countryNames = CountryNames.of(context);
_countries.sort((a, b) =>
(countryNames.data[a.isoCode.toUpperCase()] ?? "").compareTo(
countryNames.data[b.isoCode.toUpperCase()] ?? ""));
I'm not worried about the countries that aren't found in countryNames.data
-- I just filter those out of the displayed list. The problem is that in English,
Åland Islands
appears at the bottom of the forward-sorted list, and in French and other languages with a proliferation of special characters, the situation is even worse.
Is there an idiomatic way to sort strings in Dart so that special characters are treated more logically?
The core libraries in Dart are responsible for the existence of List class, its creation, and manipulation. Sorting of the list depends on the type of list we are sorting i.e. if we are sorting integer list then we can use simple sort function whereas if it is a string list then we use compareTo to sort the list.
List Contains method called sort, that function will sort the list in alphabetical order (from a to z). Technically you only need _myBranchListName. sort() to sort the array.
typedef Sort = int Function(dynamic a, dynamic b); typedef SortF = Sort Function(String sortField); SortF alphabetic = (String sortField) => (a, b){ return a[sortField]. toLowerCase(). compareTo(b[sortField]. toLowerCase()); }; SortF number = (String sortField) => (a, b) { return a[sortField].
To sort a Map , we can utilize the SplayTreeMap . Sorted keys are used to sort the SplayTreeMap . A SplayTreeMap is a type of map that iterates keys in a sorted order. SplayTreeMap is a self-balancing binary tree.
You would have to create a mapping between regular characters and characters with diacritics, and use it within the comparison such that 'Åland Islands' is considered to be 'Aland Islands' for comparison purposes.
It looks like someone else has already done that and published it as a package: https://pub.dev/packages/diacritic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With