Search code examples
stringflutteralgorithmsearchflutter-android

Flutter search on random position string


I want to search in a List of Strings, but the search query does not need to be in order as the result.

Let's say I have a list of strings

List<String> a = [
Fracture of right arm, 
Fracture of left arm, 
Fracture of right leg, 
Fracture of left leg,
];

and I want to implement a search filter that when I type fracture right the result would be

Fracture of right leg
Fracture of right arm

How do I do this in Flutter? Because flutter contains() only detects when I type fracture **of** right


Solution

  • You can try this:

    List<String> a = [
        "Fracture of right arm",
        "Fracture of left arm",
        "Fracture of right leg",
        "Fracture of left leg",
      ];
      String query = "fracture right";
    
      List<String> terms = query.toLowerCase().split(" ");
      List<String> matches = a.where(
        (el) {
          var elLower = el.toLowerCase();
          for (var term in terms) {
            if (!elLower.contains(term)) {
              return false;
            }
          }
          return true;
        },
      ).toList();
      print(matches);
    

    Note that this will find matches regardless of the order, you can modify it to disallow that.