Home > Mobile >  How to filter through list of objects like a search?
How to filter through list of objects like a search?

Time:12-16

Suppose I have this class:

class Car {
  late String make;
  late int year;

  Car({required this.make, required this.year});
}

How could I make a function that filters a list of Cars based on a query parameter?

Use this function as reference:

void filterCarsList(String query) {
  List<Car> cars = [
    Car(make: "Benz", year: 2021),
    Car(make: "BMW", year: 2016),
    Car(make: "Ford", year: 1999),
    Car(make: "Benz", year: 2009),
  ];
  List<Car> filteredList = [];

  filteredList = cars.where((e) => (e.make == query)).toList();

  print(filteredList);

  return;
}

What I am trying to do is create a search functionality. For Example: if the query == "b", then the 2 Benz and BMW objects should be in the filteredList. If the query == "be", then the 2 Benz objects should be in the filteredList.

The function currently works however the entire string of make needs to be entered. For example, query needs to equal "Benz" for the Benz objects to be returned. I'm pretty sure I need to use RegEx but I don't really know where to start with that. Any ideas?

CodePudding user response:

What you are doing is make is equal to query its means make and query should be same.

To solve this issue you need to use contains method just like this

filteredList = cars.where((e) => (e.make.toLowerCase().contains(query.toLowerCase()))).toList();

this will work for you.

CodePudding user response:

You can use contains function on the string to achieve this.

filteredList = cars.where((e) => (e.make.contains(query))).toList();

and to add the results from both the cases you can add

filteredList = cars.where((e) => (e.make.toLowerCase().contains(query.toLowercase()))).toList();
  • Related