How to use json and serialization with firebase and bloc? Error: Converting object to an encodable object failed
Asked Answered
H

1

1

this is my cloud firestore looks like: my cloud firestore here

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

used jsonSerialization for my database

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

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

  Photography();

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

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

  AllImages();

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

By running flutter pub run build_runner build in the project root, I generated JSON serialization code for my Photography and AllImages whenever they are needed.

Model.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'Model.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Photography _$PhotographyFromJson(Map<String, dynamic> json) {
  return Photography()
    ..couplePhoto = json['couplePhoto'] as String
    ..female = json['female'] as String
    ..image_url = json['image_url'] as String
    ..info = json['info'] as String
    ..male = json['male'] as String
    ..all_images = json['all_images'] == null
        ? null
        : AllImages.fromJson(json['all_images'] as Map<String, dynamic>);
}

Map<String, dynamic> _$PhotographyToJson(Photography instance) =>
    <String, dynamic>{
      'couplePhoto': instance.couplePhoto,
      'female': instance.female,
      'image_url': instance.image_url,
      'info': instance.info,
      'male': instance.male,
      'all_images': instance.all_images
    };

AllImages _$AllImagesFromJson(Map<String, dynamic> json) {
  return AllImages()
    ..imageUrl = (json['imageUrl'] as List)?.map((e) => e as String)?.toList();
}

Map<String, dynamic> _$AllImagesToJson(AllImages instance) =>
    <String, dynamic>{'imageUrl': instance.imageUrl};

After that, I created the DB class,

How to use the model class?

    class DB {
      final db = Firestore.instance;

     // Stream<QuerySnapshot> initStream() {
     //   return db.collection('photography').snapshots();
     // }

    getPhotography() async {
      return db.collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(jsonDecode(jsonEncode(Photography)));
}
    }

    DB db = DB();

my photography_bloc class

class PhotographyBloc extends BlocBase{
  //PhotographyBloc(){
  //  db.initStream().listen((data) => inFirestore.add(data));
  //}
PhotographyBloc(){
  init();
}
Photography photography;

  //final _firestoreController = StreamController<Photography>();
  //Stream<Photography> get outFirestore => _firestoreController.stream;
  //Sink<Photography> get inFirestore => _firestoreController.sink;

    final _firestoreController = StreamController<Photography>();
    Stream<Photography> get outFirestore => _firestoreController.stream;
    Sink<Photography> get inFirestore => _firestoreController.sink;

  void init() async{
    photography = db.getPhotography();
    inFirestore.add(photography);
  }


  @override
  void dispose() {
    _firestoreController.close();
  }
}

my StreamBuilder Widget How to get data using JSON serialization

                    child: StreamBuilder<Photography>(
                        stream: bloc.outFirestore,
                        initialData: null,
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Column(
                                children: buildItem(snapshot.data, bloc));
//                                children: snapshot.data.documents
//                                    .map<Widget>((doc) => buildItem(doc, bloc))
//                                    .toList());
                          } else {
                            return SizedBox();
                          }
                        }),

builderItem() method,

buildItem(Photography doc, PhotographyBloc bloc) {
...
 child: ClipRRect(
                            borderRadius: BorderRadius.circular(20.0),
                            child: FadeInImage.assetNetwork(
                              placeholder: "assets/images/photography.jpg",
                              image: doc.couplePhoto,
//                              image: doc.data['couplePhoto'],
                              fit: BoxFit.fill,
                            ),
                          ),
Humectant answered 22/6, 2019 at 6:39 Comment(1)
@pskink do you have answer my question, sir?Humectant
E
0

According to the package source :

  /// Writes to the document referred to by this [DocumentReference].
  ///
  /// If the document does not yet exist, it will be created.
  ///
  /// If [merge] is true, the provided data will be merged into an
  /// existing document instead of overwriting.
  Future<void> setData(Map<String, dynamic> data, {bool merge = false}) {
    return Firestore.channel.invokeMethod<void>(
      'DocumentReference#setData',
      <String, dynamic>{
        'app': firestore.app.name,
        'path': path,
        'data': data,
        'options': <String, bool>{'merge': merge},
      },
    );
  }

You must give a <String, dynamic> Map to setData(x) method.

So in your case you should maybe do it like this :

getPhotography() async {
      return db.collection('photography')
        .document("0yUc5QBGHNNq6WK9CyyF")
        .setData(photography.toJson());
}
Entreaty answered 23/6, 2019 at 8:32 Comment(4)
thank you for answer my question. sir, Photography.toJson can't be used. photography.fromJson is only available to use. factory Photography.fromJson(Map<String, dynamic> json) => _$PhotographyFromJson(json); Map<String,dynamic> toJson() => _$PhotographyToJson(this);Humectant
I added like this, Error is Unhandled Exception: Converting object to an encodable object failed: Photography Map<String, dynamic> data =jsonDecode(jsonEncode(Photography)); Future<Photography> postsMap = Firestore.instance .collection('photography') .document("0yUc5QBGHNNq6WK9CyyF") .setData(data);Humectant
Just figured ... The method is getPhotography... What's the purpose of this method ?Entreaty
Sorry I doesnt able to change method name..purpose of getPhotography set data..It's working..but I dont understand, how to retrieve data from firestore? I google and find this code, Photography.fromJson(jsonDecode(jsonEncode(snapshot.data))); I dont know how to use it. And where? What is snapshot.data? How ro use on bloc?Humectant

© 2022 - 2024 — McMap. All rights reserved.