skip to Main Content

I have a collection named categorymovie and each category contains a list of Movie

here now i want only list of all movies from each document’s field ‘movies’ from all category

here is firebase design

enter image description here

this is my function where i want to apply logic

void fetchMovieOnly() async {
    List<Movie> allMovies = [];
    final _db = FirebaseFirestore.instance;
    final snapshot =
        await _db.collection("MovieCategories").get();
//what code for fetching movies from querysnapshot


    
  }

here is my movie class

class Movie {
  String id;
  String name;
  Movie({required this.id, required this.name});

  toJson() {
    return {
      'Id': id,
      'Name': name,
    };
  }

  factory Movie.fromMap(Map<String,dynamic> map){
    return Movie(
      id: map['Id'],
      name: map['Name'],
    );
  }
}

2

Answers


  1. you could do something like this

    Future<List<Movie>> fetchMovieOnly() async {
          List<Movie> allMovies = [];
          final _db = FirebaseFirestore.instance;
          final snapshot = await _db.collection("MovieCategories").get();
        
          snapshot.docs.forEach((document) {
            Map<String, dynamic> data = document.data();
            if (data['movies'] != null) {
              data['movies'].forEach((movieData) {
                Movie movie = Movie.fromMap(movieData);
                allMovies.add(movie);
              });
            }
          });
          return allMovies;
    }
    
    Login or Signup to reply.
  2. void fetchMovieOnly() async {
        List<Movie> allMovies = [];
        final _db = FirebaseFirestore.instance;
        final snapshot =
            await _db.collection("MovieCategories").get().then((value) {
          for (var doc in value.docs) {
            List<dynamic> list = doc['Movies'];
    
            allMovies.addAll(list.map((e) => Movie.fromMap(e)).toList());
          }
        });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search