Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter through list of objects like a search?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading