I need help with my flutter code which involves firebasefirestore.
This is my code. I'd like to retrieve from the database the image_url from the map.
final userData = FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser.uid)
.get();
But in userData is not a map exactly.
It is a Future<DocumentSnapshot<Map<String, dynamic>>>.
This is what get returns . My question is, how do I scope into the Map<String, dynamic> ?
I mean to get the userData['image_url']... ? Because I get this error:
The operator '[]' isn't defined for the type 'Future<DocumentSnapshot<Map<String, dynamic>>>'.
Thanks alot!
As shown in the Firebase documentation on getting a document, that'd be:
final docRef = db.collection("users").doc(FirebaseAuth.instance.currentUser.uid);
docRef.get().then(
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
// ...
},
onError: (e) => print("Error getting document: $e"),
);
You can also use await as Timur commented, in which case it'd be:
final docRef = db.collection("users").doc(FirebaseAuth.instance.currentUser.uid);
DocumentSnapshot doc = await docRef.get();
final data = doc.data() as Map<String, dynamic>;
// ...
Related
I need to get data from an array in Firestore.
I'm getting an error:
StateError (Bad state: field does not exist within the DocumentSnapshotPlatform)
when I run the following query on the firestore database:
Future getData() async {
await FirebaseFirestore.instance
.collection("users")
.get()
.then((QuerySnapshot? querySnapshot) {
querySnapshot!.docs.forEach((doc) {
alldata = doc["errors"];
});
});
}
How do I properly make this query?
Try this instead :
Future getData() async {
final snapshot = await FirebaseFirestore.instance
.collection("users")
.get();
querySnapshot!.docs.forEach((doc) {
alldata = (doc.data() as Map<String, dynamic>)["errors"];
});
}
Solved!
Future getData() async {
final docRef =
await FirebaseFirestore.instance.collection("users").doc(user.uid);
docRef.get().then(
(DocumentSnapshot doc) {
alldata = (doc.data() as Map<String, dynamic>)["errors"];
print('Получен массив данных: ${alldata}');
print('Получен массив данных: ${alldata.first}');
},
onError: (e) => print("Error getting document: $e"),
);
}
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');
}
static List categoryList() {
final categorySnapshots = FirebaseFirestore.instance
.collection('categories')
.orderBy('name')
.snapshots();
List categories = [];
categorySnapshots.map((snapshot) => snapshot.docs.map((doc) {
print(snapshot.toString());
categories.add(doc.data()['name']);
}));
print(categories);
return categories;
}
Categories is empty.
How to populate it with the data from snapshots?
I added a new collection called "school", there're two items added inside the document.
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age',descending: true).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}
I used my code, and it works. Could you please remove ".where" and try it again?
You could chain where and orderBy together. Please see my code below. Reference link => Using Where and Order by different fields in Firestore query
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}
Using the below code might help
you can convert the snapshot to Map<String,dynamic> by using the following function:
static Post fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
}
I have a list of documents which all hold a coordinate as a value. How can I get all the coordinate and write them into a list. On firebase they are stored as GeoPoints. When I try to get the values from fire base I just get the following.
[Instance of 'GeoPoint', Instance of 'GeoPoint', Instance of 'GeoPoint', ..., Instance of 'GeoPoint', Instance of 'GeoPoint']
Writing to firebase (works)
_markerClick(lat, long) {
FirebaseFirestore.instance
.collection("users")
.doc(user!.uid)
.collection('userLocations')
.add({'coords': GeoPoint(lat, long)});
}
Reading from firebase
Future showMarkers() async {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(user!.uid)
.collection('userLocations')
.get();
final allData = querySnapshot.docs.map((doc) => doc.get('coords'));
print(allData);
}
That seems correct to me: each field is an instance of the GeoPoint class. If you want to get the actual latitude and longitude from the field, use the properties of that object.
querySnapshot.docs.map((doc) => "[${doc.get('coords').latitude}, ${doc.get('coords').longitude}]")
You can try this way too.
const allCoords = [];
await FirebaseFirestore.instance
.collection('users')
.doc(user!.uid)
.collection('userLocations')
.get()
.then((docs) => {
docs.forEach((doc) => {
allCoords.push({
coords: doc.get('coords'),
});
});
});
print(allCoords);
I have a users id I want to add it to firestore, like this
['GEcuHm3ICpWlEzfq1Z2tAjI2LII3', 'GEcuHm3ICpWlEzfq1Z2tAjI2LII3' ...]
I tried multiple ways but it didn't work
List membersListUid = [];
Future createGroup() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.cast() // <---
);
}
...
Future createGroupFunc() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.map((e)=> e).toList() //<---
);
...
Maybe this helps to understand the code
//Controller class
Map<String, dynamic>? userMap;
onSearch() async {
await _fireStore
.collection('users')
.where("email", isEqualTo: searchedMembers.text)
.get()
.then((value) {
userMap = value.docs[0].data();
});
update();
}
membersListUid.add({
"uid": userMap!['uid']
});
It's still gives me map within array.
THE PROBLEM:
membersListUid is a List of Maps. That is why you get an array of Maps in your database.
You need to get the actual value of the uid from each Map by using the uid key to get the value from the map.
THE SOLUTION:
Update this line:
membersListUid: controller.membersListUid.map((e)=> e).toList()
to this below:
controller.membersListUid.map((e)=> (e as Map<String, dynamic>)['uid']).toList()