Flutter Firestore getting incomplete array - flutter

I'm trying to fetch an array of strings I have saved on my database but I'm getting the array back with missing values, only the first value is shown inside of it. Here's the structure of my database:
Path: /users/uid/services <-- this is the array
Path: /services/uid <--service document
The code I'm using to retrieve the users is:
_getWorkers() async {
var query = await Firestore.instance.collection('users').where('services', arrayContains: widget.category['uid']).getDocuments();
query.documents.forEach((doc) {
workers.add(doc.data);
List<String> values = List.from(doc.data['services']);
print('services:' + values.toString());
});
var test = await Firestore.instance.collection('users').document('PtBD2EMSTodvlx6WHUx8QOHHLNA2').get();
print('actual services:' + test['services'].toString());
}
Both query and test get data back, but the services array only contains the first value.

Its difficult to answer without actually seeing the entire DB structure. But still on the outset i can see only one error with your code.
When you are trying to execute the where() call, try adding the snapshots to retrieve all relevant data.
Since await is also used, it is much better to call the listen() on it and then read the values to be added to the worker
Try using this below code in place of your first line.
await Firestore.instance.collection('users').where('services', arrayContains: widget.category['uid']).snapshots().listen((query)=>query.documents.forEach((doc)=>print(doc.data['services'])));

For some reason Firebase wasn't returning the updated array. Tested it again today and it worked with the same code. Sorry for bothering, thanks for the help anyways.

Related

Flutter get future list data into normal list

I am trying to show a list of items in a DropdownField, which requires a non-future list.
So I am trying to turn my future list (which I get from a database call) into a normal list by iterating over it and adding it to a new, normal, list, like so;
When I print the individual elements of the future list, I get results back.
But afterwards, when I print the new list, it returns as a null value.
Does anyone have any idea as to how I can solve this issue ?
PS: I am NOT interested in a FutureBuilder solution. I know that I can show a future list with a futurebuilder, but this will not fit the solution I am hoping to achieve.
Thanks in advance!
That’s because you’re not waiting for the future to complete. When you do print(newList) the future isn’t completed yet.
You will have to need to await the getAnswers data to archieve what you want.
final answers = await getAnswersList();
for (final answer in answers) {
print(answer.toString());
}
The problem is that you are not initializing newList. You are trying to add items to a null list. Change the fourth line of getAll() to the following:
var newList = List<dynamic>();
You are also not awaiting your firebase call. This means that you will print the array BEFORE you finish your firebase call. You need to make this getAll() method async and await, the firebase call so it doesn't print the null version.

Flutter save array to Firebase Database

I am making a small example with Flutter, the data is saved on Firebase Database Realtime as an array, on the client side I will download the array, display it on a list view then customize it, end the process I want to save directly that array on Firebase. But when I use the following code
myRef.set(myArray);
And error:
Unhandled Exception: Invalid argument: Instance of...
I tried converting my array to json array by the following code
String jsonArray = jsonEncode(myArray);
myRef.set(jsonArray);
then the data was set successfully, but the result was a string that appeared on Firebase, not a list I wanted.
So I can ask questions here, expect a correct answer from everyone, very respectfully
Okay i got an answer
I just create an Map<String,dynamic> to repersent for each item in myArray and put it to List like that
List<Map<String,dynamic>> result = new List<Map<String,dynamic>>();
myArray.forEach((item) {
result.add(item.toJson());
});
And final, i just set 'result' for Firebase
stepRef.set(result);
Thank you for reading :D

CRUD flutter/firestore/firebase

I am new to coding and what I am trying to achieve is to set up a method that checks the 'MONDAY' collection inside post and if the data exist? the values of the fields get updated otherwise they get created! I have been stuck for a while now and been redirected to different solutions but nothing has worked for me. I appreciate all help
Future<void> createPostMonday(Post post) async{
await postsRef.document(post.authorId).collection('Monday').setData({
'alOne':post.alOne,
'alTwo':post.alTwo,
'alThree':post.alThree,
'alFour':post.alFour,
'alFive':post.alFive,
'alSix':post.alSix,
'beOne':post.beOne,
'beTwo':post.beTwo,
'beThree':post.beThree,
'beFour':post.beFour,
'beFive':post.beFive,
'beSix':post.beSix,
'likes': post.likes,
'authorId': post.authorId,
'timestamp': post.timestamp,
});
setData() is used to write the contents of a single document whose ID you already know. It requires that you use a DocumentReference object to locate that document.
If you're trying to add a new document to a collection with a unique random ID, you should use add() method of a CollectionReference.
await postsRef.document(post.authorId).collection('Monday').add(...)

Firestore collections snapshot wont convert to csv

I am trying to convert my firestore collection to csv format so i can email it in the code.
I am doing it the following way:
_sendMail() async{
List tempList = await Firestore.instance
.collection("transactions")
.snapshots()
.toList();
print(tempList.toString());
final res = const ListToCsvConverter().convert(tempList);
print(res.toString());
}
The async function never prints the templist and res so im assuming it gets stuck at collection retrieving part.
I know the firestore collection works because i retrieve documents from it in other parts of the app.
I am using the csv package for converting to csv format which requires a list: https://pub.dev/packages/csv
Does anyone know if im doing it wrong or theres another way to do it?
It's not stuck, even if it's offline, Firestore has offline mode and won't wait for anything. Probably tempList is empty, which is why you don't see anything printed.

Meteor - Cannot Access All Read Operations

I'm new to Meteor. I've been stuck on this problem for a while. I can successfully adds items to a collection and look at them fully in the console. However, I cannot access all of the read operations in my .js file.
That is, I can use .find() and .findOne() with empty parameters. But when I try to add .sort or an argument I get an error telling me the object is undefined.
Autopublish is turned on, so I'm not sure what the problem is. These calls are being made directly in the client.
This returns something--
Template.showcards.events({
"click .play-card": function () {
alert(Rounds.find());
}
})
And this returns nothing--
Template.showcards.events({
"click .play-card": function () {
alert(Rounds.find().sort({player1: -1}));
}
})
Sorry for the newbie question. Thanks in advance.
Meteor's collection API works a bit differently from the mongo shell's API, which is understandably confusing for new users. You'll need to do this:
Template.showcards.events({
'click .play-card': function() {
var sortedCards = Rounds.find({}, {sort: {player1: -1}}).fetch();
console.log(sortedCards);
}
});
See this for more details. Also note that logging a cursor (the result of a find) probably isn't what you want. If you want to see the contents of the documents, you need to fetch them.
Rounds.find().sort({player1: -1}) returns a cursor, so you will want to do this:
Rounds.find().sort({player1: -1}).fetch();
Note that this returns an Array of document objects. So you would do something more like this:
docs = Rounds.find().sort({player1: -1}).fetch();
alert(docs[0]);