【问题标题】:Array type Field in firestore document to be converted to List of custom objectsFirestore 文档中的数组类型字段将转换为自定义对象列表
【发布时间】:2020-04-29 12:46:47
【问题描述】:

我的 firebase 上的数据如下所示:

我想将 LIST_OF_ALL_COLLEAGUES 转换为列表,但我不知道该怎么做。

我有一个用户类,它有这个列表同事字段。 我的用户类转换代码如下所示:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';
import 'package:snagsnapper/Data/colleague.dart';

class User {
  User ({
    this.name,
    this.dateFormat,
    this.listOfALLColleagues,
  });

  String name;
  String dateFormat='dd-MM-yyyy';
  List<Colleague> listOfALLColleagues;

  User.fromMap(DocumentSnapshot data)
      : this(
    name: data[NAME],
    dateFormat: data[DATE_FORMAT],
    listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
  );

  Map<String, dynamic> toJSON() => {
    NAME : name,
    DATE_FORMAT : dateFormat,
    LIST_OF_COLLEAGUES : listOfALLColleagues,
  };

}

我的同事类如下所示:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:snagsnapper/Contants/constants.dart';

class Colleague {
  String name;
  String email;
  String phone;
  String uniqueID;

  Colleague({
    this.name,
    this.email,
    this.phone,
    this.uniqueID,
  });

  Colleague.fromMap(DocumentSnapshot data)
      : this(
    name: data[NAME],
    email: data[EMAIL],
    phone: data[PHONE],
    uniqueID: data[UID],
  );

  Map<String, dynamic> toJSON() => {
    NAME : name,
    EMAIL : email,
    PHONE : phone,
    UID : uniqueID,
  };
}

到目前为止,我已经尝试了几种我在网上看到的方法,但都没有运气: 我试过了:

listOfALLColleagues: List<Colleague>.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.from(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: List.castFrom(data[LIST_OF_COLLEAGUES]),
listOfALLColleagues: data[LIST_OF_COLLEAGUES] as List<Colleague>,
listOfALLColleagues: data[LIST_OF_COLLEAGUES]
        .map((value) {
          return Colleague.fromMap(value);
        }).toList(),

我知道其中一些是相同的,但我只想在这里提及它们。

【问题讨论】:

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

我设法用 Json-Serial 库做到了。我之前并不知道这个库,我发现这样更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多