skip to Main Content

I am learnign firebase , here i have just added some data to firebase collection but now i am failing to make factory constructor for getting data from fire base as document snapshot as i dont know how to deal for converting documentSnapshot to model class

thanks if you can implement and code for factory constructor


class Movie {
  String id;
  String name;

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

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

  
}


class MovieCategory {
  String id;
  String name;
  List<Movie> movies;

  MovieCategory({required this.id, required this.name, required this.movies});

  toJson() {
    return {
      'Id': id,
      'Name': name,
      'Movies': movies.map((e) => e.toJson()).toList(),// check also this..is it ok?
    };
  }

  factory MovieCategory.fromSnapshot(
      DocumentSnapshot<Map<String, dynamic>> document) {
//dont know how to code for this..and it should return empty object if data is null..


}
}

List<MovieCategory> movieCategoryList = [
  MovieCategory(
    id: '1',
    name: 'BollyWood',
    movies: [
      Movie(id: '1', name: 'Hindi 1'),
      Movie(id: '2', name: 'Hindi 2'),
    ],
  ),
  MovieCategory(
    id: '2',
    name: 'HollyWood',
    movies: [
      Movie(id: '1', name: 'English 1'),
      Movie(id: '2', name: 'English 2'),
    ],
  )
];

4

Answers


  1. add this to your MovieCategory class

    factory MovieCategory.fromSnapshot(
          DocumentSnapshot<Map<String, dynamic>> document) {
    
        final data=document.data()!;
        return MovieCategory(
            id: data['Id'],
            name: data['Name'],
          movies: (data['Movies'] as List<dynamic>).map((e) => Movie.fromMap(e)).toList()
            );
    
      }
    

    and aslo fromMap method to your Movie class

     factory Movie.fromMap(Map<String,dynamic> map){
        return Movie(
          id: map['Id'],
          name: map['Name'],
        );
      }
    
    Login or Signup to reply.
  2. Extract the map from document and use it same, like you do with regular fromMap/fromJson method:

    factory MovieCategory.fromSnapshot(
          DocumentSnapshot<Map<String, dynamic>> document) {
        Map<String, dynamic>? map = document.data();
    
        return MovieCategory(
          id: map['id'] ?? '',
          name: map['name'] ?? '',
          movies: map['movies'] != null
              ? (map['movies'] as List<dynamic>)
                  .map((e) => Movie.fromJson(e))
                  .toList()
              : [],
        );   }
    
    Login or Signup to reply.
  3. Data obtained from Firebase in the snapshots is in the form of a JSON Map<String, dynamic>, which could have as many nested fields, i.e. those "dynamic" values could be of any type including other Map<String, dynamic>.

    The easiest way for dealing with this is letting the library json_serializable just generate the code for you by annotating you class. This way you avoid forgetting adding fields or errors and typos.

    
    import 'package:json_annotation/json_annotation.dart';
    
    part 'movie.g.dart';
    
    @JsonSerializable()
    class Movie {
      String id;
      String name;
    
      const Movie({required this.id, required this.name});
    
      static Movie fromJson(Map<String, dynamic> json) => _$MovieFromJson(json);
      
      Map<String, dynamic> toJson() => _$MovieToJson(this);
    }
    
    @JsonSerializable()
    class MovieCategory {
      String id;
      String name;
      List<Movie> movies;
    
      MovieCategory({required this.id, required this.name, required this.movies});
    
      static MovieCategory fromJson(Map<String, dynamic> json) => _$MovieCategoryFromJson(json);
    
      Map<String, dynamic> toJson() => _$MovieCategoryToJson(this);
    }
    

    Then wherever you are getting your document snapshot:

    try {
      final MovieCategory movieCategory = MovieCategory.fromJson(docSnapshot.data()!);
    } catch (e, s) {
      // TODO: Log your parsing error
    }
    
    Login or Signup to reply.
  4. factory MovieCategory.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> document) {
      Map<String, dynamic>? data = document.data();
    
      if (data == null) {
        return MovieCategory(id: '', name: '', movies: []);
      }
    
      List<dynamic>? movieDataList = data['Movies'];
      List<Movie> movies = [];
    
      if (movieDataList != null) {
        movies = movieDataList
            .map((movieData) => Movie(id: movieData['Id'], name: movieData['Name']))
            .toList();
      }
    
      return MovieCategory(
        id: data['Id'],
        name: data['Name'],
        movies: movies,
      );
    }
    

    The MovieCategory class now includes the fromSnapshot factory constructor, which enables the conversion of a DocumentSnapshot from Firestore into a MovieCategory object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search