Justin Dosaj
Justin Dosaj

Reputation: 587

How to retrieve value of child data from firebase DB?

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: enter image description here

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.

Upvotes: 0

Views: 126

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80914

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");

Upvotes: 1

Justin Dosaj
Justin Dosaj

Reputation: 587

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)

Upvotes: 0

Related Questions