如何在Firebase和Bloc中使用json和序列化?错误:将对象转换为可编码对象失败 [英] How to use json and serialization with firebase and bloc? Error: Converting object to an encodable object failed

查看:160
本文介绍了如何在Firebase和Bloc中使用json和序列化?错误:将对象转换为可编码对象失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的云存储库,看起来像:

this is my cloud firestore looks like:


错误消息:未处理的异常:将对象转换为可编码的
对象失败:摄影

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

我的数据库使用了jsonSerialization

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

通过运行 flutter pub run build_runner build 在项目根目录中,无论何时需要,我都会为我的Photography和AllImages生成JSON序列化代码。

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};

此后,我创建了 DB类

如何使用模型类?

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

我的photography_bloc班

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();
  }
}

我的StreamBuilder小部件
如何获取数据使用JSON序列化

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()方法,

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,
                            ),
                          ),


推荐答案

根据软件包来源:

  /// 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},
      },
    );
  }

您必须给< String,dynamic> 映射到 setData(x)方法。

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());
}

这篇关于如何在Firebase和Bloc中使用json和序列化?错误:将对象转换为可编码对象失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆