Flutter retrieve all documents in the sub-sub-Collection in firebase - flutter

my nested collections looks like this:
User--> drugs--> drugsTime
I want to retrieve all the documents in the subsub-collection (drugsTime) for specific drug however I dont know the drug document id so I did the following :
getData() async {
final User? user = FirebaseAuth.instance.currentUser;
final _uid = user?.uid;
var drugID = "";
final QuerySnapshot<Map<String, dynamic>> querySnapshot =
await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection('drug')
.where("drugName", isEqualTo: widget.title)
.get();
querySnapshot.docs.forEach((element) async {
drugID = element.id;
});
final QuerySnapshot<Map<String, dynamic>> querySnapshot2 = (await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection("drug")
.doc(drugID)
.get()) as QuerySnapshot<Map<String, dynamic>>;
querySnapshot2.docs.forEach((element) async {
drugTime .add (element.get('time'));
isTaken.add(element.get("isTaken"));
});
print(drugTime);
print(isTaken);
}
but this error ocurr:
E/flutter (24517): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_JsonDocumentSnapshot' is not a subtype of type 'QuerySnapshot<Map<String, dynamic>>' in type cast
E/flutter (24517): #0 _historyState.getData (package:taafi_application_v1/pages/history.dart:38:17)
E/flutter (24517): <asynchronous suspension>
the problem shows in
as QuerySnapshot<Map<String, dynamic>>;
how can i solve it ?

Here, you casted DocumentSnapshot with QuerySnapshot, where will return QuerySnapshot and doc will return DocumentSnapshot.
Your code of method getData should be as following
getData() async {
final User? user = FirebaseAuth.instance.currentUser;
final _uid = user?.uid;
var drugID = "";
final QuerySnapshot<Map<String, dynamic>> querySnapshot =
await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection('drug')
.where("drugName", isEqualTo: widget.title)
.get();
querySnapshot.docs.forEach((element) async {
drugID = element.id;
});
final DocumentSnapshot<Map<String, dynamic>> doc = await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection("drug")
.doc(drugID)
.get();
drugTime.add (doc.data()!['time']);//Make sure time has value
isTaken.add(doc.data()!['isTaken']);
print(drugTime);
print(isTaken);
}
Please make sure of which you are requested for.

Related

type 'Future<Null>' is not a subtype of type 'String' in type cast in flutter and Firebase

I am trying to query list by mentioned location in user document.
1. All_Data is a main Collection in Firebase.
2. User_In is a SubCollection inside a document in a main collection in Firebase.
3. Area is a Field in a Document which stores user Area in String form.
final user_loc = FirebaseFirestore.instance
.collection('All_Data')
.doc(user.uid)
.collection('User_In')
.doc(user.uid)
.get()
.then((value) async {
print(await value.get('Area'));
}) as String;
final Stream<QuerySnapshot> datastream = FirebaseFirestore.instance
.collection('All_Data')
.where("private", isEqualTo: false)
.where("Area", isEqualTo: user_loc)
.snapshots();
Here is What I want...
Every User has their own specific area mentioned in subcollection('User_In').doc(user.uid), I want Streambuilder to show only those documents from the main collection that contains Area is equal to the Area in subcollection('User_In').doc(user.uid).
Here is What I tried...
I have Mentioned the code above, I am trying to insert values to query them in the final stream datastream
Here is What I get...
Error I am Getting is "type 'Future' is not a subtype of type 'String' in type cast".
I am new to it please help me with what needs to be done, Or is it just fundamentally not possible with Firebase.
You can get it like
() async {
final value = await FirebaseFirestore.instance
.collection('All_Data')
.doc(user.uid)
.collection('User_In')
.doc(user.uid)
.get();
final user_loc = value.get('Area') as String?;
}
Edit:
class _FaState extends State<Fa> {
Future<String?> fetchUserloc() async {
final value = await FirebaseFirestore.instance
.collection('All_Data')
.doc(user.uid)
.collection('User_In')
.doc(user.uid)
.get();
final user_loc = value.get('Area') as String?;
return user_loc;
}
Future<Stream<QuerySnapshot>> getMyStream() async {
final user_loc = await fetchUserloc();
return FirebaseFirestore.instance
.collection('All_Data')
.where("private", isEqualTo: false)
.where("Area", isEqualTo: user_loc)
.snapshots();
}
late final userStreamFuture = getMyStream();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
FutureBuilder<Stream<QuerySnapshot>>(
future: userStreamFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
// you will get the steam here
}
return CircularProgressIndicator();
},
)
],
),
);
}
}

_TypeError (type 'Null' is not a subtype of type 'FutureOr<String>')

I am trying to fetch profile image from firestore. But it is giving an error.
Here is the code of fuction which is use to get the image from database. Kindly help if you can
Future<String> getUserImage() async {
final uid = auth.currentUser?.uid;
final users = await firestore
.collection("app")
.doc("user")
.collection("driver")
.doc(uid)
.get();
return users.data()?['dp'];
}
Your getUserImage method cant return null, you can return default value return users.get('dp')?? "got null";
or accept nullable data
Future<String?> getUserImage() async {
final uid = auth.currentUser?.uid;
final users = await firestore
.collection("app")
.doc("user")
.collection("driver")
.doc(uid)
.get();
return users.get('dp');
}
Try the following code:
Future<String> getUserImage() async {
final String uid = auth.currentUser!.uid;
final DocumentSnapshot<Map<String, dynamic>> users = await firestore
.collection("app")
.doc("user")
.collection("driver")
.doc(uid)
.get();
return users.get('dp');
}

async function not completing when querying FirebaseFirestore

See the print statement down below. It never executes.
Future<void> populate() async {
final userId = FirebaseAuth.instance.currentUser!.uid;
final db = FirebaseFirestore.instance;
// Get list of ids of parties use swiped on.
var snapshot1 = await db
.collection("partiers_swipes")
.where('userId', isEqualTo: userId)
.get();
var partyIdsUserSwipesOn = [];
if (snapshot1.size > 0) {
snapshot1.docs.forEach((element) {
partyIdsUserSwipesOn.add(element.data()['partyId']);
});
}
var snapshot2 = await db
.collection("parties")
.where(FieldPath.documentId, whereNotIn: partyIdsUserSwipesOn)
.get();
print('This never executes');
}
The whereNotIn argument is not supported by the where clause. This crashes the function.

Flutter firestore append another QuerySnapshot

how do I append another QuerySnapshot to a QuerySnapshot?
static final CollectionReference _col = FirebaseFirestore.instance.collection('post');
Stream<QuerySnapshot<Object?>> query = _col.where('firstReleaseDate', isLessThanOrEqualTo: Timestamp.now()).snapshots();
QuerySnapshot ss = await _col
.query() <-----append here
.orderBy(field, descending: isDescending)
.startAfterDocument(lastDoc)
.limit(limit)
.get()
.timeout(TIMEOUT_DURATION);

How to check if subcollection exists in Firestore with Flutter future<bool>

I have a problem with return true/false statement from Firestore query if some sub-collection exists.
Here is my code:
Future<bool> checkIfCollectionExist(
String collectionName, String productId) async {
await _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get()
.then((value) {
return value.docs.isNotEmpty;
});
}
As a result I get Instance of Future<bool>, but I need true/false answer.
What I doing wrong here ?
Use
Future<bool> checkIfCollectionExist(String collectionName, String productId) async {
var value = await _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get();
return value.docs.isNotEmpty;
}
Or
Future<bool> checkIfCollectionExist(String collectionName, String productId) {
return _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get()
.then((value) {
return value.docs.isNotEmpty;
});
}