skip to Main Content

I have search field that filter my list and it works fine, but I want to filter list by multiple elements

My list:

List<Product> _p = [
  Product(
   title : 'P1',
   info : 'just Football',
   seller : 'me',
  ),
  Product(
   title : 'P2',
   info : 'just Football',
   seller : 'other',
  ),
]

filter method

List<Product> filterByText(text){
    return _p.where((element) =>
        element.title.contains(text) ||
        element.info.contains(text) ||
        element.seller.contains(text)
  ).toList();
}

I want, when I type Football other in TextFormField, to get this item:

Product(
 title : 'P2',
 info : 'just Football',
 seller : 'other',
),

Instead, it returns an empty list. It worked when I type just other. How can I filter with multiple elements by single string?

2

Answers


  1. There are many ways to do this. I’ll go with one approach:

    You can implement Product‘s toString() method like so:

    @override
    String toString() {
      return '$title $info $seller'; // You can add other fields here if needed.
    }
    

    Now, implement a fuzzy search, for filterByText. To do this, you can use an existing package like https://pub.dev/packages/fuzzywuzzy.

    List<Product> filterByText(text) {
      return extractTop(
        query: text,
        choices: _p,
        cutoff: 10, // You can choose another cutoff
        // You can choose another number of results
        // or show all using a different method
        limit: 4,
        getter: (x) => x.toString(),
      ).map((result) => result.choice).toList();
    }
    

    You don’t have to necessarily implement toString() you can also just write '${x.title} ${x.info} ${x.seller}' in the getter field of extractTop directly.

    Login or Signup to reply.
  2. You can break down the initial search query into words and then search all the words. Combine the results at the end.

    String searchQuery = 'Some Query With Multiple Words';
    List<String> queryWords = searchQuery.split(' ');
    List<Product> results = [];
    for(String word in queryWords){
      final filterResult = filterByText(word);
      results.addAll(filterResult);
    }
    
    results = results.toSet().toList(); // to remove duplicates
    

    Please ensure you override the == for class Product.

    This might help you further: multiple word search in flutter

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