如何使用JSON和序列化与火力和集团? 错误:转换对象的可编码对象失败(How to use j

2019-10-29 02:37发布

这是我的云计算公司的FireStore的样子:

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

使用jsonSerialization我的数据库

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在项目的根,我生成的JSON序列代码为我的摄影和AllImages每当需要它们。

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类

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序列得到的数据

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

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

Answer 1:

据包源:

  /// 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)方法。

所以你的情况,你也许应该去做这样的:

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


文章来源: How to use json and serialization with firebase and bloc? Error: Converting object to an encodable object failed