skip to Main Content

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

2

Answers


  1. You can try this code:

    var aFilter = a.where((p0) => (p0.toLowerCase().contains("fracture of right")).toList();
    

    And you get a new list with the filtered elements.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search