I'm using the Drift package in my Flutter project, and I need some help with a search feature in a DropdownSearchwidget. I have a table called ingredients defined like this:
class Ingredients extends Table {
TextColumn get id => text()();
TextColumn get ingredientName => text()();
TextColumn get code => text()();
RealColumn get glucides => real()();
}
I want to allow users to search ingredients from this table using a dropdown with a search field. Here's the dropdown implementation:
DropdownSearch<Ingredient>(
selectedItem: ing,
key: dropDownkey,
decoratorProps: DropDownDecoratorProps(
decoration: InputDecoration(
hintText: 'Search field',
hintStyle: GoogleFonts.lexend(
fontWeight: FontWeight.w400,
fontSize: 12.sp,
color: AppColors.greyLight,
),
border: InputBorder.none,
),
),
items: (String? filter, _) {
if (filter == null || filter.trim().isEmpty) {
return ingredients; // Default list
}
final cleanedTerms = filter
.split(RegExp(r'\s+'))
.map((term) => term.replaceAll(RegExp(r'[^\w\s]+'), '').toLowerCase())
.where((term) => term.isNotEmpty)
.toList();
return db.searchIngredients(cleanedTerms);
},
itemAsString: (Ingredient ingredient) => ingredient.ingredientName,
onChanged: (Ingredient? selectedIngredient) {
if (selectedIngredient != null) {
int index = controllers.indexOf(controller);
addOrUpdateIngredientWithGlucose(
ingredients: [selectedIngredient],
totalMass: controller.text.isNotEmpty
? double.parse(controller.text)
: 0,
index: index,
);
}
},
compareFn: (i1, i2) => i1?.id == i2?.id,
popupProps: const PopupProps.menu(
menuProps: MenuProps(backgroundColor: AppColors.white),
showSearchBox: true,
fit: FlexFit.loose,
constraints: BoxConstraints(),
),
)
And here’s the searchIngredients function in my Drift database:
Future<List<Ingredient>> searchIngredients(List<String> userInput) async {
if (userInput.isEmpty) return [];
final query = select(ingredients);
query.where((ingredient) {
return userInput.map((term) {
MyLogger.info('term: $term');
MyLogger.info('ingredient: ${ingredient.ingredientName}');
return ingredient.ingredientName.like('%$term%');
}).reduce((value, element) => value | element);
});
return query.get();
}
What I need help with:
- The dropdown doesn’t always return expected results when searching for multi-word inputs.
- Is my LIKE search in Drift correct for searching multiple keywords?
when I search on 'white sugar' I got result but when I search on 'sugar white' I got no result