Sort List by alphabetical order

后端 未结 4 767
野的像风
野的像风 2020-12-09 10:05

I\'m trying to sort a list by alphabetical order and tried porting something i had in javascript to flutter. But it gives me an exception on String that it does not have the

相关标签:
4条回答
  • 2020-12-09 10:46

    Thanks to Remi's answer, I extracted this as a Function.

    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].compareTo(b[sortField]);
        };
    

    with this you can write.

    list.sort(alphabetic('name')); //replace name with field name
    
    list.sort(number('name')); //replace name with field name
    
    0 讨论(0)
  • 2020-12-09 10:50

    late answer, i had a similar situation and here is how i solved it

         String a = 'towNnpBiDHRehMh4FhYAYShVFr62';
      String b = 'Yjeq9bA0spdZGmqlbr4J663LyvC3';
      String c = "RdeQo32uUwX3ftBeGm0nFChkzE52";
    //if you try to sort the strings without converting them toLowercase ir uppercase you will get different results.
      List<String> _myBranchListName = [
        a.toLowerCase(),
        b.toLowerCase(),
        c.toLowerCase(),
      ];
    
      _myBranchListName.sort();
    //if you want to add to strings from the result
      var userId = "${_myBranchListName[0]}" + "${_myBranchListName[1]}";
      print(userId);
    
      print(_myBranchListName);
    
    0 讨论(0)
  • 2020-12-09 10:56

    I found the best way to sort a list alphabetically is this:

          List.sort((a, b) => a.toString().compareTo(b.toString()));
    
    0 讨论(0)
  • 2020-12-09 10:57

    < and > is usually a shortcut to a compareTo method.

    just use that method instead.

    data.sort((a, b) {
      return a['name'].toLowerCase().compareTo(b['name'].toLowerCase());
    });
    
    0 讨论(0)
提交回复
热议问题