Reputation: 21
Based on the firestore database, I've created my own user model.
class ReceiverModel {
final String id;
final String name;
final String contactNumber;
final String bloodGroup;
final String city;
final String accepted;
ReceiverModel({ this.id, this.name, this.contactNumber, this.bloodGroup, this.city, this.accepted });
}
And, in my database file I added a stream to get all the data:
// Receiver List from snapshot
List<ReceiverModel> _receiverListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.documents.map((doc){
return ReceiverModel(
id: doc.data['id'] ?? '',
name: doc.data['name'] ?? '',
contactNumber: doc.data['contactNumber'] ?? '',
bloodGroup: doc.data['bloodGroup'] ?? '',
city: doc.data['city'] ?? '',
accepted: doc.data['accepted'] ?? '',
);
}).toList();
}
//get receiverCollection stream
Stream<List<ReceiverModel>> get receivers {
return receiverCollection.snapshots()
.map(_receiverListFromSnapshot);
}
@override
Widget build(BuildContext context) {
return StreamProvider<List<ReceiverModel>>.value(
initialData: List(),
value: ReceiverDatabaseService().receivers,
child: SafeArea(
class _ReceiverListState extends State<ReceiverList> {
@override
Widget build(BuildContext context) {
final receivers = Provider.of<List<ReceiverModel>>(context);
return ListView.builder(
itemCount: receivers.length,
itemBuilder: (context, index) {
return ReceiverTile(receiverModel: receivers[index]);
},
);
}
}
Then I used it to pass data through my screens, and later on I displayed all the data that came throuh the stream by a listview. Anyways, my question is, now as I'm showing all data, I want to create a search button to display any specific bloodGroups or any specific cities, not all the datas. How can I do that?
return StreamProvider<List<ReceiverModel>>.value(
initialData: List(),
value: ReceiverDatabaseService().receivers,
Upvotes: 0
Views: 152
Reputation: 1010
You can use Firestore Query methods against a collection reference to query particular Document Records
The various options you have to query data are like where
, limit
, orderBy
, etc. API Reference
Edit - Takes in input whether you want to fetch all data or search it In your case, you can change snapshots functions to something like this
Stream<List<ReceiverModel>> fetchReceivers({String bloodGroup}) {
var query = receiverCollection;
if(bloodGroup!=null)
query = query.where("bloodGroup",isEqualTo:bloodGroup);
return query.snapshots().map(_receiverListFromSnapshot);
}
For adding a search button with a strict search you can call the function with the typed-in value.
I hope I have solved your query. Thanks and have a good day
Upvotes: 1