Flutter FireStore Query Using status - firebase

Using the below code in my flutter app, It can display all the delivery details in my correction;
Stream<QuerySnapshot> getUsersShippingStreamSnapshots(
BuildContext context) async* {
final uid = await Provider.of(context).auth.getCurrentUID();
yield* Firestore.instance
.collection('userData')
.document(uid)
.collection('newShipping')
.orderBy('placedDate', descending: true)
.snapshots();
}
Now, I want to display only the delivery details which has delivered status, but I'm getting an error using this code;
Stream<QuerySnapshot> getUsersShippingStreamSnapshots(
BuildContext context) async* {
final uid = await Provider.of(context).auth.getCurrentUID();
yield* Firestore.instance
.collection('userData')
.document(uid)
.collection('newShipping')
.where('status', isEqualTo: 'pending')
.orderBy('placedDate', descending: true)
.snapshots();
Help me fix this code.

Related

Dart/Flutter Firestore allow multiple values for a field in a query

I started learning dart / flutter on my own initiative.
I have encountered one problem, which I have been trying to solve for the last 3 days.
It is about reading data from the firestore.
There are a lot of documents in the firestore.
I need a way to read data from multiple query.
I read the data with the streambuilder, and display it with the listview builder.
HomeScreen:
StreamBuilder<List<Vehicle>?>(
stream: database.vehicleStream(user.uid, filters),
builder: (context, snapshot) {
if (snapshot.hasData) { ...
Datebase Service:
Stream<List<Vehicle>?> vehicleStream(String uid, List<ScoutFilter> filters) {
vhTest(uid, filters);
final path = APIPath.vehicle();
final reference = FirebaseFirestore.instance
.collection(path)
.where('datetime', isGreaterThan: limitedTime())
.where('brand', isEqualTo: 'Mercedes-Benz')
.where('model', isEqualTo: 'SL 350')
.orderBy('datetime', descending: true)
.limit(100);
final snapshots = reference.snapshots();
//print(snapshots);
return snapshots.map((snapshot) => snapshot.docs
.map(
(snapshot) => Vehicle.fromMap(snapshot.data(), snapshot.id),
)
.toList());
This works when it comes to one query for "Mercedes-Benz", "SL 350".
How do I improve this and have more query for about 30 different vehicles?
Eg.
.where('brand', isEqualTo: 'Tesla')
.where('model', isEqualTo: 'Model 3')
.where('brand', isEqualTo: 'Audi')
.where('model', isEqualTo: 'Q3')
.where('brand', isEqualTo: 'Renault')
.where('model', isEqualTo: 'Clio')
etc.
You should use the whereIn, as in:
.where('brand', whereIn: ['Tesla', 'Audi', 'Renault'])
See this link

Download Data from firebase in flutter

I want to build a contactScreen for my flutter app. Therefor I have to download an array from Firebase. I am just able to download directly into a listView in flutter and get stuck while coding. Heres my code:
var currentUser = FirebaseAuth.instance.currentUser!.uid;
var contacts;
getUserData() async {
var userData = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: currentUser)
.get();
contacts = userData['contacs']; //heres the error
}
At first I want to initialize the currentUser's UID and then get the currentUser's contacts array from firebase. Therefor I build the getUserData() method to download the User and then initialize his contacts array.
The last step doesn't work in Flutter, I can't access the contacts array. Is the way I want to get the data correct?
You're at the very least missing an await before the get() call:
var userData = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
.get();
Without await your userData is of type Future<QuerySnapshot<Map<String, dynamic>>> as you get in the error message. By using await, its type will become QuerySnapshot<Map<String, dynamic>>.
you need to call await or use FutureBuilder
like this
FutureBuilder(
future: FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
.get(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: [Text(snapshot.data['name'])], //error here
);
}
return Loading();
},
)

How to add data from a subcollection in Firestore to a List?

FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
print(info.toString());
}
I am trying to build a Flutter application using Firestore.My firestore has two collections namely users and friends.Collection users contains documents with locations,names and Collection friends contains documents which each have a subcollection friends that store the Unique IDs of "users" who are friends. This is the output when I execute the above function
I/flutter ( 7773): hello eyHBWGrNoxSMe8cQUqWC
I/flutter ( 7773): []
I/flutter ( 7773): lalala{loc: Instance of 'GeoPoint', dname: hamza ansari}
PROBLEM: The data is not getting stored into the list 'info'. Any help with this would be appreciated :D
.Here is a photo of the friends collection.
And here is a photo of the users collection.
Would really love it if someone could help me out here :)
You can access the documents by snapshot.data.documents then you can get document Id like this
var doc= snapshot.data.documents;
var docId=doc[index].documentID
FirebaseFirestore.instance
.collection('dishes')
.doc(docId)
.collection('ingredients')
.snapshots(),
i think the problem is that you are simply not returning anything in your Future.
try this
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
return info ;
}
The problem seems to be with the conversion of the subcollection to a list. Try the following:
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(Map(Map.fromMap(value.data())));
});
});
});
print(info.toString());
}

firebase query is returning null, when chaining .where isEqualTo and isGreaterThanOrEqualTo together

I am querying the next 7 days task for individual users. And getting value first then null. When I chain multiple where.
Code:
Query query = collectionReference
.where('authorID', isEqualTo: userID)
.where('dueDateTime', isGreaterThanOrEqualTo: startDay)
.where('dueDateTime', isLessThanOrEqualTo: endDay);
console output:
flutter: [Instance of 'Task', Instance of 'Task']
flutter: [Instance of 'Task', Instance of 'Task']
flutter: [Instance of 'Task', Instance of 'Task']
flutter: null
If I remove .where('authorID', isEqualTo: userID) I am getting my value.
startDay and endDay are both DateTime. I did try with Timestamp.fromDate(startDay). Also didn't work with isGreaterThanOrEqualTo or isLessThanOrEqualTo individually.
meaning
.where('authorID', isEqualTo: userID)
.where('dueDateTime', isGreaterThanOrEqualTo: startDay);
or
.where('authorID', isEqualTo: userID)
.where('dueDateTime', isLessThanOrEqualTo: endDay);
Doesn't work.
Whole code:
Stream<List<Task>> getNextDaysTasks({
#required String userID,
#required DateTime startDay,
#required DateTime endDay,
}) {
CollectionReference collectionReference = reference.collection('tasks/');
Query query = collectionReference
.where('authorID', isEqualTo: userID)
.where('dueDateTime', isGreaterThanOrEqualTo: startDay)
.where('dueDateTime', isLessThanOrEqualTo: endDay);
final Stream<QuerySnapshot> snapshots = query.snapshots();
final result = snapshots.map((collectionSnapshot) => collectionSnapshot.docs
.map((documentSnapshot) => Task.fromMap(documentSnapshot.data()))
.toList());
return result;
}
UI code:
StreamBuilder<List<Task>>(
stream: DatabaseService().getNextDaysTasks(
userID: auth.user.uid,
startDay: today,
endDay: seventhDay,
),
builder: (context, snapshot) {
final tasks = snapshot.data ?? [];
print(snapshot.data);
return CatagoryCard(
title: 'Next 7 Days',
taskCount: '${tasks.length}',
screen: Next7Days(),
);
}),
My database:

Function returning null in FLutter

I am trying to implement the function below but it gives me null.
To be specific, Future credit() is not updating the variable value. There is no problem with the database because if I put print(doc['value']) instead of value += doc['value'], I get the expected result.
It seems, getCredit() is the one returning null.
Future credit() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final String uid = user.uid;
int value = 0;
Firestore.instance
.collection('entries')
.where("uid", isEqualTo: uid)
.where("type", isEqualTo: "+")
.orderBy("time", descending: true)
.snapshots()
.listen((data) => data.documents.forEach((doc) => value += doc['value']));
print(value); // doesnt update value
return value;
}
int getCredit() {
credit().then((value) {print(value);});
credit().then((value) {return value;}); // return mot working
}
Thanks!
try this:
Future<int> getCredit() async {
return await credit();
}
Fixed it. It seems it was a problem with the scope of variable.
int cr = 0;
Future credit() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final String uid = user.uid;
Firestore.instance
.collection('entries')
.where("uid", isEqualTo: uid)
.where("type", isEqualTo: "+")
.orderBy("time", descending: true)
.snapshots()
.listen((data) => data.documents.forEach((doc) {cr = cr + doc['value'];}));
print('$cr');
}

Resources