Retrieve data of an array - firebase

I want to retrieve data of an array that stores url's and place them, each one, in an item in a list. In my example, all url's are stored in the first item. Is there a way to manipulate the field indexes todo this?
[https://i.stack.imgur.com/KnIF6.png][1].
Here's my code:
Future<void> getImages() async {
int i = 0;
listImgs = List(4);
await firestoreInstance
.collection('dados_inst')
.where('cod_inst', isEqualTo: codInst)
.get()
.then((value) {
value.docs.forEach((snapshot) {
listImgs[i++] = snapshot.get('list_view');
});
});
for (i = 0; i < 4; i++) {
print(listImgs[i]);
}
}

A simple way is to convert the value.docs list to a map, and use the forEach method of that, which gets both the index and the value:
value.docs.asMap().forEach((index, snapshot) {
listImgs[index] = snapshot.get('list_view');
});
See also:
Enumerate or map through a list with index and value in Dart

Related

get a map value by key from a list of maps in dart flutter

I need to get the value of a data when the name matches the key in a list of maps.
Something like this:
List<Map> dataList = [];
await friends.doc("+2348******").collection("Friends").get().then((value) {
for (var element in value.docs) {
dataList.add(element.data());
}
print("${dataList.where((element) => element == "+23789900")}");
});
I expect this to print out: John doe
I found something similar but they didnt solve my problem
Process a list of map to get a value of a key in the map
Dart/Flutter How to access element of Map inside a list
Dart: Return string value from list of maps
Get a single key value from a list of maps
Try this example:
List<Map> dataList = [];
await friends.doc("+2348******").collection("Friends").get().then((value) {
for (var element in value.docs) {
dataList.add(element.data());
}
dataList.forEach((element){
if(element['name'] == "+2348******"){
//print
}
})
});
I think you should try this code... Hopefully, it goes well... works with normal map at the moment.
List<Map> dataList = [];
await friends.doc("+2348******").collection("Friends").get().then((value) {
for (var element in value.docs) {
dataList.add(element.data());
}
//Try this code
var key = dataList.keys.firstWhere((k)
=> countries[k] == '+23789900', orElse: () => null);
print(key); //output: 35
});

How can i return a List as Future<List>? - Flutter

im trying to randomly get documents from firebase. Since .where(FieldPath.documentId, whereIn: element) only supports lists of 10 elements i split my list to sublists and run each query based on the sublists. When result from each query is returned i try adding them to an List<DocumentSnapshot<Object?>> results = [];
This List is then returned and my problem is that the screen displays error, but if i reload the screen it works. I think the problem is that my function wants to return
Future<List<DocumentSnapshot>> getBeerPongCards1() async {
But my List is List<DocumentSnapshot<Object?>> results = [];
Future<List<DocumentSnapshot>> getBeerPongCards1() async {
List<DocumentSnapshot<Object?>> results = [];
List<String> IdList = List<String>.generate(20, (counter) => "$counter");
IdList.shuffle();
List<List<String>> subList = [];
for (var i = 0; i < IdList.length; i += 10) {
subList.add(
IdList.sublist(i, i + 10 > IdList.length ? IdList.length : i + 10));
}
subList.forEach((element) async {
await FirebaseFirestore.instance
.collection('beerpong1')
.where(FieldPath.documentId, whereIn: element)
.limit(10)
.get()
.then((value) async {
results.addAll(value.docs);
});
});
return results;
}
I dont know if my question made any sense but im thankful for any help:D
The issue is likely that when you use sublist.forEach, that for loop is not awaited, so you return an empty list (in any case, that should be handled in a graceful way for the user).
Instead of using a .forEach function, use a regular for loop - That way, each element will be awaited properly, and the list will be populated when the function returns:
for (final element in subList) {
await FirebaseFirestore.instance
.collection('beerpong1')
.where(FieldPath.documentId, whereIn: element)
.limit(10)
.get()
.then((value) async {
results.addAll(value.docs);
});
}

How to check if string already exists in list?

Im trying to create a list of string which has array from firebase . And that works perfectly. But now I wanna filter the list a bit . So what I want is add allhastags one time . So if a hashtags exist twice I wanna just put it int he list once. Heres my code
Future<List<String>> getHashtags() async {
List<String> allVideoHastags = [];
QuerySnapshot snapshots =
await FirebaseFirestore.instance.collection('videos').get();
for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
List<String> videoHastags =
List.from(videoSnapshot.data()['Hashtagsforallvideos']);
allVideoHastags.addAll(videoHastags);
}
_allResults = allVideoHastags;
searchResults();
return allVideoHastags;
}
So before adding the hashtags into the list ,I wanna check if it already exists in the list of strings .Hope anyone can help .If you need more information please leave a comment
Just loop over the hashtags you get from firebase and add them to your results only if they are not already in there like this:
Future<List<String>> getHashtags() async {
List<String> allVideoHastags = [];
QuerySnapshot snapshots =
await FirebaseFirestore.instance.collection('videos').get();
for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
List<String> videoHastags =
List.from(videoSnapshot.data()['Hashtagsforallvideos']);
videoHastags.forEach((element) {
if(!allVideoHastags.contains(element)){
allVideoHastags.add(element);
}
});
}
_allResults = allVideoHastags;
searchResults();
return allVideoHastags;
}
This would remove all duplicates from a list
_allResults = allVideoHastags.toSet().toList();
YOUR_LIST.forEach((element) => if(element == "YOUR_STRING") {YOUR_NEW_LIST.add(element )});

Accessing nested collections and document in Firebase (Flutter)

If you cannot understand the title I am very sorry. I am new to NoSQL don't know how to address this problem.
i am having a nested collection inside my firebase database.
first collection
clicking on '145'
clicking on 'location'
in the chargepoints method I have hardcoded (.doc('WPHW9669')) instead of that I have to loop through the 145 collection and get the document first. after that I have to go inside that looped document to access the 'location' collection.
this is the code which needs to be modified:
chargePoints() {
_db
.collection('bus')
.doc('Routes')
.collection('145')
.doc('WPHW9669') // this the place where the first iteration have to occur
.collection('location')
.orderBy('updatedTime', descending: true)
.limit(1)
.get()
.then((docs) {
if (docs.docs.isNotEmpty) {
for (int i = 0; i < docs.docs.length; i++) {
LatLng position = LatLng(
docs.docs[i].data()['position']['geopoint'].latitude,
docs.docs[i].data()['position']['geopoint'].longitude);
print(docs.docs[i].data()['position']['geopoint'].latitude);
initMarker(position, docs.docs[i].id);
// notifyListeners();
// initMarker(docs.docs[i].data(), docs.docs[i].id);
}
}
});
}
So I found the answer that I am looking for.
instead of creating a complicated collection, I change my collection to be simple.
new collection URL - 145/(Bus NO)/location/
final result = FirebaseFirestore.instance.collection('145');
busPoint() {
result.get().then((snapshot) {
snapshot.docs.forEach((element) {
chargePoints(element.id.toString());
print(element.id);
});
});
}
the above method will loop through the '145' collection and call the chargePoints() method for each bus no's found(i registered the bus no as the document id).
chargePoints(String element) {
_db
.collection('145')
.doc(element)
.collection('location')
.orderBy('updatedTime', descending: true)
.limit(1)
.get()
.then((docs) {
if (docs.docs.isNotEmpty) {
for (int i = 0; i < docs.docs.length; i++) {
LatLng position = LatLng(
docs.docs[i].data()['position']['geopoint'].latitude,
docs.docs[i].data()['position']['geopoint'].longitude);
initMarker(position, docs.docs[i].id);
}
}
});
}

Flutter: Get Firebase Database reference child all data

I have a firebase database child which content is like below:
How to retrieve this in flutter?
My Current code:
static Future<Query> queryUsers() async{
return FirebaseDatabase.instance
.reference()
.child("zoom_users")
.orderByChild('name');
}
queryUsers().then((query){
query.once().then((snapshot){
//Now how to retrive this snapshot? It's value data giving a json
});
});
To retrieve the data try the following:
db = FirebaseDatabase.instance.reference().child("zoom_users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values["name"]);
});
});
Here first you add the reference at child zoom_users, then since value returns data['value'] you are able to assign it to Map<dynamic, dynamic> and then you loop inside the map using forEach and retrieve the values, example name.
Check this:
https://api.dartlang.org/stable/2.0.0/dart-core/Map/operator_get.html
Flutter: The method forEach isn't defined for the class DataSnapshot
query.once().then((snapshot){
var result = data.value.values as Iterable;
for(var item in result) {
print(item);
}
});
or with async that you already use
var snapshot = await query.once();
var result = snapshot.value.values as Iterable;
for(var item in result) {
print(item);
}

Resources