Unhandled Exception: Converting object to an encodable object failed: Photography

Viewed 7061

my cloud_firestore looks like this:

all_images:{imageUrl:[]}, couplePhoto:String, female:String, image_url:String, info:String, male:String

my model class:

import 'package:json_annotation/json_annotation.dart';
part 'Model.g.dart';

@JsonSerializable()
class Photography {
  final List<AllImages> all_images;
  final String couplePhoto;
  final String female;
  final String image_url;
  final String info;
  final String male;

  Photography(this.all_images, this.couplePhoto, this.female, this.image_url,
      this.info, this.male);

  factory Photography.fromJson(Map<String, dynamic> json) =>
      _$PhotographyFromJson(json);

  Map<String, dynamic> toJson() => _$PhotographyToJson(this);
}

@JsonSerializable()
class AllImages {
  final List<String> imageUrl;

  AllImages(this.imageUrl);

  factory AllImages.fromJson(Map<String, dynamic> json) =>
      _$AllImagesFromJson(json);

  Map<String, dynamic> toJson() => _$AllImagesToJson(this);
}

Currently, I haven't adminPanel to data insert. so, now I need to read data. When running this database, the error is coming in here.

    Future<Photography> postsMap = Firestore.instance
        .collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(jsonDecode(jsonEncode(Photography)));
2 Answers

At this line:

.setData(jsonDecode(jsonEncode(Photography)));

You are referencing the Type object for the Photograph class, instead you need to pass an instance (so you would need to call the constructor with the required values, and pass the result of that).

.setData(jsonDecode(jsonEncode(Photography(<pass-in-constructor-args-here>))));

if you are using json_serialization library be careful. sometimes the generated method in your case "_$AllImagesToJson()" not working properly. look inside this. I know that json_serialization library is not working properly in terms of generic objects

Related