Reputation: 597
I am building an application that is supposed to create a movie library for you. I have set up my firebase database to store the movie title and all the movie specifications inside the database like so:
The next step I want to take is reading only the movie titles (Official Secrets, Seberg, Unbreakable Kimmy Schmidt) to make a list displaying the movie titles to the user. I tried using
void readData()
{
DBRef.once().then((DataSnapshot datasnapshot){
print('DATA SNAPSHOT NEXT LINE');
print(datasnapshot.value);
});
}
But grabs all the data inside my firebase database when I only want the titles. How do I grab only the titles? Then following that, if a user selects a title I then want to go into the database and grab all the information that falls under that title. For example:
I have also tried:
void readData()
{
DBRef.child('Official Secrets (2019)').once().then((DataSnapshot datasnapshot)
{
print('DATA SNAPSHOT NEXT LINE');
print(datasnapshot.value);
});
}
I used this to try to test to grab only the title of the movie, but this returns null.
Upvotes: 1
Views: 1220
Reputation: 124
You have to do something like this. But your data structure are not good
List<String> readData()
{
List<String> titleList = new List()
Map<String,String> map = new Map();
DBRef.once().then((DataSnapshot datasnapshot){
print('DATA SNAPSHOT NEXT LINE');
print(datasnapshot.value);
map = datasnapshot.value();
map.forEach((key,value){
map.add(key);
continue;
})
});
return titleList;
}
Upvotes: 1
Reputation: 1277
Unfortunately, the simple answer is you can't. Not with the current schema. Due to the way data is organized in RTDB, it's not possible to fetch only the movie title without fetching the child data of the entire node.
What you'd have to do right now is called data flattening i.e avoid deep nesting to avoid fetching the entire data of the node. This guide on structuring data might help.
You can create an additional node called movie_titles
and keep all your movie titles there and keep the reel-house
node as it is.
Now, you always fetch the movie_titles
node initially without getting all the data and show the titles in your app. When the user taps a particular title in your app, then fetch the corresponding data from the reel-house
node.
Your DB might look somewhat like this
movie_titles:[
"title 1",
"title 2",
"title 3",
"title 4",
],
reel-house: [
"title 1": {
// data for title 1
},
"title 2": {
// data for title 2
},
"title 3": {
// data for title 3
},
"title 4": {
// data for title 4
},
],
Upvotes: 1