Reputation: 149
so I'm using getx to to fetch data from firebase to a listview card where in i have multiple data on it and i want to search by any data that is present on the card to filter out a specific card that is searched by any of its value.
class BookController extends GetxController {
static BookController instance = Get.find();
late CollectionReference collectionReference;
RxList<BookModel> books = RxList<BookModel>([]);
//search
RxList<BookModel> foundBooks = RxList<BookModel>([]);
@override
void onInit() {
super.onInit();
collectionReference = firebaseFirestore.collection("books");
books.bindStream(getAllBooks());
//search
foundBooks.value = books;
}
void filterBooks(String bookName) {
List<BookModel> results = [];
if (bookName.isEmpty) {
results = books;
} else {
results = books
.where((element) => element["name"]
.toString()
.toLowerCase()
.contains(bookName.toLowerCase()))
.toList();
}
foundBooks.value=results;
}
Stream<List<BookModel>> getAllBooks() => collectionReference.snapshots().map(
(query) => query.docs.map((item) => BookModel.fromMap(item)).toList());
}
filterBooks function is used in searchBar widget as:
onChanged: (value) => controller.filterBooks(value),
Upvotes: 0
Views: 1282
Reputation: 2825
Assuming BookModel
looks something like this:
class BookModel {
String name;
String year;
String callNo;
}
var searchFor = 'SearchForMe';
searchFor = searchFor.toLowerCase();
foundBooks.clear();
foundBooks.addAll(books.where((book) =>
book.name.toLowerCase().contains(searchFor)
|| book.callNo.toLowerCase().contains(searchFor)
|| book.year.toLowerCase().contains(searchFor)
|| ( ... )
));
Upvotes: 0