· Developer as a hobby

Implement Fuzzy search in your flutterflow project

Everybody has tried the simple search or how to make efficient search or having more control over the results from a search.
I used a package from pub.dev that could be helpful for many of you (i hope so).

I will leave a link with the package and i will explain how does it work and if someone wants to implement it in different ways, i will just post the way i'm using it if you have any other doubts or questions or need help you can contact me.

summary: two arguments, list of documents and word/term to search. It searches over the field you want it to search(within the document) and returns the documents that matched with the term.

Hope this helps someone!

https://pub.dev/packages/fuzzy

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:fuzzy/fuzzy.dart';

Future<List<ItemsRecord>> searchItemCode(
  List<ItemsRecord> listToSearch,
  String searchTerm,
) async {
// Create an empty list to save results
  List<ItemsRecord> searchResult = [];
  try {
//Create an empty list of Strings to save the field from the document you want to search
    List<String> codeList = [];
//Add fields from each document to the list of strings
    for (final item in listToSearch) {
      codeList.add(item.code.toString());
    }
//setting up fuzzy search, stating list of strings you want it to search and something important is the threshold 0 is match perfect, so basically 0.5 will give you quite good results you can play with it for see how you like it more
    final fuse = Fuzzy(
      codeList,
      options: FuzzyOptions(
        findAllMatches: true,
        tokenize: true,
        threshold: 0.5,
      ),
    );
//Create the results
    final result = fuse.search(searchTerm);
//Loop on the results check to which document it belongs, add this document to the variable to return to the user and remove it for next iterations and it does not repeat.
    result.forEach((r) {
      for (final product in listToSearch) {
        if (r.item == product.code.toString()) {
          searchResult.add(product);
          listToSearch.remove(product);
          break;
        }
      }
    });
  } catch (e) {
    debugPrint("Error: $e");
  }
//Return the list of documents that matched 
  return searchResult;
}
8
4 replies