stringflutterlistdartsorting

Sort List of Strings by having a character Flutter


I have a List of strings ["pana", "open","peno","alp","palp"]

and i need to sort them by having the letter "p", then alphabetically:

so the result should be ["pana", "palp","peno", "open","alp"]

How can i do this in Flutter


Solution

  • This is quite a roundabout way of doing it but:

      var list = [
        "pana",
        "open",
        "peno",
        "alp",
        "palp",
        "kk",
        "can",
        "aaa",
        "111"
        ,"zs",
        "sz",
      ];
      
      var pattern = 'p';
      
      var listStartsWith = list.where((word) => word.startsWith(pattern)).toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    
      var listContains = list
          .where((word) => word.contains(pattern) && !word.startsWith(pattern))
          .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
      
        var listContainsNot = list
          .where((word) => !word.contains(pattern) && !word.startsWith(pattern))
          .toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    
      var reoderedList = [...listStartsWith, ...listContains, ...listContainsNot];
      
      print(reoderedList);
    

    I will update once I've been able to optimise it but we can work off this for now.