I have a searchDelegate and when user searches, I use the list.where to fetch accordingly, now that I have that down, I have an issue where when user doesn't include some characters like a comma or apostrophe or hypen, it doesn't show those results, EXAMPLE I have a book in my list with title => 'Tis you I want, O Juliet.
when user searches without the apostrophe, or even misses the comma, it won't show that book unless you type it character for character, I want a case where I can make the where() method
ignore the user's ignorance if you get me... here's some code snippet.
import 'package:flutter/material.dart';
import 'book.dart';
import 'book_brain.dart';
class MyDelegate extends SearchDelegate<Book> {
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
},
);
}
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
query.isEmpty ? Navigator.pop(context) : query = '';
},
),
];
}
@override
Widget buildResults(BuildContext context) {
return const Center();
}
@override
Widget buildSuggestions(BuildContext context) {
List<Book> suggestions = BookBrain().allBooks().where((book) {
final result = book.bookText.toLowerCase();
final input = query.toLowerCase();
final result2 = book.bookTitle.toLowerCase();
//here I wanna make it ignore when user misses certain characters
return result.contains(input) || result2.contains(input);
}).toList();
return ListView.builder(
itemCount: suggestions.length,
itemBuilder: (context, suggestIndex) {
final suggestion = suggestions[suggestIndex];
return ListTile(
title: Text(suggestion.bookTitle),
trailing: Text('${suggestion.authorName} ${suggestion.bookYear}',
style: const TextStyle(
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w300,
),
),
onTap: () {
close(context, suggestion);
},
);
});
}
}
CodePudding user response:
You can accomplish this with a regex. result
and result2
will have all spaces and special characters removed.
// "It's in 4 hours." -> "itsin4hours"
final result = book.bookText.replaceAll(RegExp('[^A-Za-z0-9]'), '').toLowerCase();
final result2 = book.bookTitle.replaceAll(RegExp('[^A-Za-z0-9]'), '').toLowerCase();
More detailed example here