How to query firestore in real time in flutter - flutter

I have this code
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef = _firestore
.collection("users")
.where("id", isEqualTo: "hhjhgjhfhgfhgfh");
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get("username");
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}
But am faced with this issue,
Please I need solution

where(...) function return Query<Map<String, dynamic>> not the DocumentReference
You need to pass the document path (DocumentReference) in the get() method. So, specify the correct document path
DocumentReference userRef = _firestore.collection('users').doc('hhjhgjhfhgfhgfh');
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef =
_firestore.collection('users').doc('hhjhgjhfhgfhgfh');
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get('username');
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}

Related

Instance of 'Future<String?>' flutter

Why is returning Instance of 'Future<String?>' instead String value?
Future<String?> getUser() async {
User user = await FirebaseAuth.instance.currentUser!;
FirebaseFirestore firestore = await FirebaseFirestore.instance;
String uid = user.uid;
String? userName;
// to get username from firebase
return firestore
.collection("users")
.doc(uid)
.get()
.then((value) {
if (value.exists) {
var data = value.data();
userName = data?["name"];
print("There is data :$userName");
} else {
print("There no Data!");
}
return Future.value(userName);
});
}
I am trying to get String value?
The place you like to get data from this method use await & the method is needed to be async. like
_myFunction() async{
final value = await getUser();
Also I will suggest to not mixing await and .then.
Future<String?> getUser() async {
User user = FirebaseAuth.instance.currentUser!;
FirebaseFirestore firestore = FirebaseFirestore.instance;
String uid = user.uid;
String? userName;
// to get username from firebase
final value = await firestore.collection("users").doc(uid).get();
if (value.exists) {
var data = value.data();
userName = data?["name"];
print("There is data :$userName");
} else {
print("There no Data!");
}
return userName;
}

Instance of 'Future<Map<dynamic, dynamic>>'

the problem that am trying to get value from "getThatWishlist" but it returns instead "Instance of 'Future<Map<dynamic, dynamic>>'"
Future<Map<dynamic, dynamic>> getThatWishlist(String? wishlistname) async {
FirebaseFirestore db = FirebaseFirestore.instance;
return await db
.collection('wishlists')
.doc(currentUserId)
.get()
.then((snapshot) async {
if (snapshot.data() == null) {
return {};
} else {
Map<dynamic, dynamic> wishlistData = {};
wishlistData =
await snapshot.data()!['userWishlists'][wishlistname]['UserItems'];
return wishlistData;
}
});
}
void createWishlistForSharedUser(String? ShareUid) async {
FirebaseFirestore db = FirebaseFirestore.instance;
await db.collection('wishlists').doc(ShareUid).set({
'sharedWishlistsWithUser': {
wishlistName: {
'UserItems': {getThatWishlist(wishlistName) //the problem is here
}
},
'wishlist owner email': currentUserEmail,
},
}, SetOptions(merge: true));
}
How to fix that problem ?
You should do something like this instead:
void createWishlistForSharedUser(String? ShareUid) async {
/// add this line
var userItems = await getThatWishlist(wishlistName);
FirebaseFirestore db = FirebaseFirestore.instance;
await db.collection('wishlists').doc(ShareUid).set({
'sharedWishlistsWithUser': {
wishlistName: {
/// update line below
'UserItems': {userItems}
},
'wishlist owner email': currentUserEmail,
},
}, SetOptions(merge: true));
}

Results are different when application tested on a physical phone and on simulator

I am trying to solve an issue with my application. When I test it on a virtual device (iPhone), the query is working well and I am getting the document I am supposed to get. When I test the application on my physical phone, the application does not find any record.
I have checked the filters, they are the same. it is exactly the same code. I have never have this situation before. Please, do you have any suggestion?
Future myQuery ( time, energy, urgent, important ) async{
final uid = FirebaseAuth.instance.currentUser!.uid;
final path = 'Users/$uid/allTasks';
final currentQuery = FirebaseFirestore.instance.collection(path);
Query statusQuery = currentQuery.where('status', isEqualTo: 'Inbox');
// Query contextQuery = statusQuery.where('context', isEqualTo: );
Query timeQuery = statusQuery.where('time_Needed', isEqualTo: time);
Query energyQuery = timeQuery.where('energy_Needed', isEqualTo: energy);
Query urgentQuery = energyQuery.where('urgent', isEqualTo: urgent);
Query importantQuery = urgentQuery.where('important', isEqualTo: important);
final snapshot = await importantQuery.get();
final data = snapshot.docs;
if(data.isNotEmpty) {
return snapshot;
}
}
ElevatedButton(child:
const Text('FIND'),
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
EngageDisplayTasks(
time: timeSelectedPicker!, energy: energySelectedPicker!,
urgent: urgentWhere, important: importantWhere,
)));
}
),
#override
void initState() {
super.initState();
myQuery(time,energy,urgent,important).then((results) {
setState(() {
querySnapshot = results;
});
});
queryEngage(time,energy,urgent,important).then((results) {
setState(() {
querySnapshot = results;
});
});
}
Future queryEngage (time,energy,urgent,important) async {
await myQueryV2();
await myQueryV3 (statusQuery,time);
await myQueryV4 (timeQuery,energy);
await myQueryV5 (energyQuery,urgent);
await myQueryV6 (urgentQuery,important);
}
Future myQueryV2 ( ) async{
final uid = FirebaseAuth.instance.currentUser!.uid;
final path = 'Users/$uid/allTasks';
final currentQuery = FirebaseFirestore.instance.collection(path);
statusQuery = currentQuery.where('status', isEqualTo: 'Inbox');
return statusQuery;
}
Future myQueryV3 (statusQuery, time) async {
timeQuery = statusQuery.where('time_Needed', isEqualTo: time);
return timeQuery;
}
Future myQueryV4 (timeQuery, energy) async {
energyQuery = timeQuery.where('energy_Needed', isEqualTo: energy);
return energyQuery;
}
Future myQueryV5 (energyQuery, urgent) async {
urgentQuery = energyQuery.where('urgent', isEqualTo: urgent);
return urgentQuery;
}
Future myQueryV6 (urgentQuery, important) async {
importantQuery = urgentQuery.where('important', isEqualTo: important);
print ('urgent: $urgent');
print ('important: $important');
print ('time: $time');
print ('energy: $energy');
final snapshot = await importantQuery.get();
final data = snapshot.docs;
if(data.isNotEmpty) {
return snapshot;
}
}
You could write a single compound query like this. It is not necessary to get the results at each stage based on the code shown. You may need to create some composite indexes to improve optimization, but Firebase should notify you automatically if this is the case.
Future myQuery ( time, energy, urgent, important ) async{
final uid = FirebaseAuth.instance.currentUser!.uid;
final path = 'Users/$uid/allTasks';
final currentQuery = FirebaseFirestore.instance.collection(path);
try {
final snapshot = currentQuery
.where('status', isEqualTo: 'Inbox')
.where('time_Needed', isEqualTo: time)
.where('energy_Needed', isEqualTo: energy)
.where('urgent', isEqualTo: urgent)
.where('important', isEqualTo: important);
await snapshot.get().then((data) {
for (var doc in data.docs) {
print("${doc.id} => ${doc.data()}");
}
});
} catch (err) {
print(err);
}
}

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.

How to Update fields using where conditions Current user = Key ( User ID) firestore and flutter

Hello I'm using flutter and firebase so I have firestore I have on collocation name Institutes and in document has names of Institutes and my Fields I have profile data ….no I need update some fields by where conditions where currant user = Key User id in the fields*
Screenshot
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
final snapshot = await Firestore.instance.collection("Institute")
.document(_Institute_name.text).get();
if (snapshot.exists) {
print(this name is existd);
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}
Okay try this
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
QuerySnapshot snapshot = await Firestore.instance
.collection('Institute')
.where('user id', isEqualTo: iduser)//I think this is your field name from the
//picture it looks like theres a space in it
.getDocuments();
if (snapshot != null) {
Map<String,dynamic> document = snapshot.documents[0].data;
//Then you would reference this by document['fieldName']
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}