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 )});
Related
How to passing the list of image to next page i try to declare at the top of code and do like this but it said
PostView({File? keepImage}) : this.keepImage = keepImage ?? [];
'keepImage' isn't a field in the enclosing class.
Try correcting the name to match an existing field, or defining a field named
i have keep image into
final List<File> keepImage = [];
and here is pick image function
Future<void> chooseImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
keepImage.add(File(pickedFile!.path));
});
if (pickedFile?.path == null) retrieveLostData();
}
Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
keepImage.add(File(response.file!.path));
});
} else {
print(response.file);
}
}
There are several ways you can do this.
The easiest is using shared preferences to store the image url in cache and so you can retrieve it wherever you want. Another is using arguments, when navigating to the other page, pass the id of this image for it.
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
I am trying to grab the children data from a certain movie title in a database, but I can only get an output of "Instance of Datasnapshot."
Here is the setup of the DB with the highlighted information I am trying to store in a list:
I tried using the following code with no success:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await DBRef.child("Movies").child(movieName).once().then((DataSnapshot datasnapshot)
{
print(datasnapshot.value.toString());
});
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value){
moviesList.add(key);
print('My-Key $key');
print('Movie List: $moviesList');
});
return moviesList;
}
Note: I am passing the selected movie name so I only grab the child information from the movie the user selects. This portion is correctly, if the user clicks on the list tile of Batman, the title will be passed to this getMovieDetails() function.
Try the following:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await FirebaseDatabase.instance
.reference()
.child("Movies")
.child(movieName)
.once();
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value) {
moviesList.add(value);
print('My-Key $key');
print('My-Value $value');
});
return moviesList;
}
}
You dont have to use then() since you are using await. Also when you call this method, you need to do for example:
await getMovieDetails("Batman");
I will make the above answer as correct, but the biggest issue was when I did:
moviesList.add(key)
When it should be:
moviesList.add(value)
Is there any way to fetch data from Firebase with an array of documents.
Now I do this with loop. It works but maybe there is some more efficient way to fetch data? Members list can contain up to 10k users so create 10k requests seems wrong.
Many thanks!
ref = db.collection('users');
Future<List<User>> fetchAllMembers({List<dynamic> members}) async {
List<User> results = [];
for (String userID in members) {
await ref.document(userID).get().then((result) {
results.add(User.fromMap(result.data, result.documentID));
});
}
return results;
}
SOLVED
So simple :). Working example below. Many thanks!
final Firestore db = Firestore.instance;
ref = db.collection('users');
List<dynamic> membersIDS = ['DSGSGSG', 'IBIOSCP3S', 'ASDUASDGU'];
/// Fetch members list
Future<List<User>> fetchAllMembers({List<dynamic> membersIDS}) async {
/// With whereIn
var result = await ref.where('uid', whereIn: members).getDocuments();
var documents = result.documents.map((doc) => User.fromMap(doc.data, doc.documentID)).toList();
return documents;
/// With loop
// List<User> results = [];
// for (String userID in members) {
// await ref.document(userID).get().then((result) {
// results.add(User.fromMap(result.data, result.documentID));
// });
// }
// return results;
}
Query documents where the given field matches any of the comparison values
userRef.where('id', 'in',
[['DSGSGSG', 'IBIOSCP3S', 'ASDUASDGU']]);
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);
}