Read key value from array using document id (Flutter) - flutter

Very new to flutter. I want to retrieve arrays of notifications using a specific document id and display [date, message, type] in my App. Tried to google but can't seem to find any solution.

Try this with this you will get specific document's data.
firebaseFirestore.collection('Customer').doc('paste-your-document-id').get();
you'll get whole data of Notification data then use it accordingly.

Whole Notification data will print.
FirebaseFirestore.instance.collection("Customer").doc(document_id).get().then((value) {
Map<dynamic, dynamic> map = value.data();
for(var element in map.values) {
element.asMap().forEach((index, firebaseValue) {
print(index);
print('${firebaseValue['Date']}');
print('${firebaseValue['Message']}');
print('${firebaseValue['Type']}');
});
}
}
);

Related

How can I get the document from Firebase Firestore with particular value in field?

I'm creating todo list in which I'll have two lists one for incomplete tasks and another for completed tasks...I'm able to retrieve the data from Firestore by pulling the whole data without any condition, but for the uncompleted list, I want to retrieve the document only with particular field values. For example, each document contains the following fields as shown in the picture:
Here is the code which I've used to get the data from firebase firestore:
static List<Task> getTasks() {
//convert firebase collection to list
List<Task> tasks = [];
FirebaseFirestore.instance.collection('Todos').snapshots().listen((data) {
data.docs.forEach((doc) {
tasks.add(Task.fromMap(doc.data()));
});
});
return tasks;
}
I want similar function like this to retrieve only documents with taskStatus == true. So, I can store all those tasks which have taskStatus of true on separate list and display them accordingly.
You can use the where function. It works like below.
For more: Cloud FireStore Filtering
FirebaseFirestore.instance
.collection('Todos')
.where('taskStatus', isEqualTo: true)
.snapshots().listen((data) {
data.docs.forEach((doc) {
other_tasks.add(Task.fromMap(doc.data()));
});
});

Read nested data from firebase realtime database in flutter

If you see the screenshot of my database, the data is stored in a nested way (cartProduct is a key which has a value of an entire Json file with keys: "id", "price" etc.). In my code, I create a map of each record in the "Orders" table in order to retrieve key values of any key that I specify. This is done by specifying the key name in the databaseMapper variable.
I am trying to read the value of each "id" and store it in a list called "testerList". I am able to store each orderNum, totalAmount or any of those key values that I specify in the databaseMapper. However, if I specify ["id"] it does not work.
I did some research and saw that the only way to reference nested items in a map is by using the logic: databaseMapper["cartProduct"]["id"] like I did below, but I keep getting an error (see last screenshot).
Any help would be appreciated!
Future _readItemIDsTest() async {
//Stores each record in the table as a map
var snapshot = await _dbRef.child("Orders").get();
snapshot.children.forEach((childSnapshot) {
var databaseMapper = childSnapshot.value as Map;
testerList.addAll([databaseMapper["cartProduct"]["id"]]);
});
print(testerList);
}
Nvm, I figured it out. The code below solved my issue.
Future _readItemIDsTest() async {
//Stores each record in the table as a map
//Adds the itemName value of each item from the map
var snapshot = await _dbRef.child("Orders").get();
snapshot.children.forEach((childSnapshot) {
databaseMapper = childSnapshot.value as Map;
var cartProductList = databaseMapper["cartProduct"];
(cartProductList as List).forEach((cartProductElement) {
testerList.addAll([cartProductElement["id"]]);
});
});
print(testerList);
}

How to arrange documents in Firestore using Flutter through custom document IDs?

I want to order the documents in Firestore. The default Firestore documents list consist of alphabetic characters which get created automatically. But I don't want that. I just want to see my newly added document added at the top of my documents list. How do I do that in flutter? It would be very helpful if you provide me with a code for that. The code I use to create a collection is:
Future<void> userSetup() async {
String user = FirebaseAuth.instance.currentUser?.displayName as String;
CollectionReference users = FirebaseFirestore.instance.collection(user);
final hours = time?.hour.toString().padLeft(2, '0');
final minutes = time?.minute.toString().padLeft(2, '0');
users.add({
"customerId": FirebaseAuth.instance.currentUser?.uid.toString(),
"customerName": FirebaseAuth.instance.currentUser?.displayName,
"customerEmail": FirebaseAuth.instance.currentUser?.email,
"selectedTime": '${hours}:${minutes}',
"selectedDate": DateFormat('dd/MM/yyyy').format(date!),
});
return;
}
But I am unable to set my own document id. Please help me with the issue. Thanks in Advance
From the Flutterfire documentation, the set() method is the one you should be using to be able to specify your own document IDs instead of add(). Keep in mind that if the document ID you specify already exists in your database, the whole existing document will be replaced. This is a sample usage as found in the documentation:
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> addUser() {
return users
.doc('ABC123')
.set({
'full_name': "Mary Jane",
'age': 18
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
It seems that documents are ordered alphabetically in the Firestore console, so your custom document IDs should follow alphabetical order as you require. Not to be confused with retrieving documents from Firestore in a particular order, which is done with the orderBy() method.

How to add a timestamp to my array/List in firestore?

I wish to generate a scatter plot using time on the x-axis from user generated submissions. To do so I am making a list of maps in which each map is the user submission and contains a timestamp field. The issue is that I cannot add a timestamp using the arrayUnion. This issue was mentioned in this post:
Link1
You can't use FieldValue.serverTimestamp() as the value to union (add) or >remove, to or from, an array type value of a document field. If you want to >use that timestamp value, you need to pass it directly to a field you're >updating or setting.
So,to solve my problem I need to update directly the field for timestamp after I have already added some data which has a form similar to below and I only need to add to the last element/Map of my List/array of Maps but I do not know how long this list currently is:
myList[{Map1}{Map2}{Map3}...{examplefield:'Some data', timstamp:null}]
final Map submissionMap = submissionData.toMap();
//Running a firestore transaction...
final DocumentReference areaDocument = Firestore.instance.document('Space/SAJJEED');
Firestore.instance.runTransaction((Transaction tx) async {
DocumentSnapshot postSnapshot = await tx.get(areaDocument);
if (postSnapshot.exists) {
//Adds the data except for the timestamp needed
await tx.update(areaDocument, <String, dynamic>{'$status': FieldValue.arrayUnion([submissionMap])});
//Insert Code for directly accessing the timestamp field and adding Timestamp
}
});```
Any other workarounds would be appreciated as well.

Add snapshot items to array without looping or forEach

Using Firestore, I can assign items to an array with the following:
this.Svc.getCategories().valueChanges().subscribe(categories => {
this.categories = categories;
})
However, this listens for changes on the items and would add them to the array on a change.
Using
this.Svc.getCategories().get().subscribe(categories => {
categories.forEach(category => {
this.categories.push(category.data())
});
})
allows me to add the items to an array without listening for changes.
However, this method required me to either use forEach or a loop to push the data into the array.
Is there a way to get a one-time snapshot of the data and assign the data to an array without looping and using push()?
Check out the Firestore docs for reading data once https://firebase.google.com/docs/firestore/query-data/get-data