Home > database >  Flutter search on random position string
Flutter search on random position string

Time:11-21

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related