Solved: How to filter through list of objects like a search?


Asked by camelCaseIsGoodPractice on December 16, 2021 (source).

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();



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?


Question answered by Rahul s (source).

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.