firebase - 数组类型将在Firestore文档中的字段转换为自定义对象列表

标签 firebase flutter dart google-cloud-firestore

我的Firebase上的数据如下所示:
enter image description here

我想将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,
  };

}

我的同事类(class)如下所示:
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(),

我知道其中有些是一样的,但我只想在这里提及。

最佳答案

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

关于firebase - 数组类型将在Firestore文档中的字段转换为自定义对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61502142/

相关文章:

dart - 如何将 flutter 连接到 Bluestacks 模拟器?

firebase - 我导航到屏幕后,signOut()不起作用..但是当我不导航时,它可以工作..如何解决此问题?

firebase - 找不到 Ionic 4 和 Firebase 页面

firebase - 如何使用 Firebase_Auth 和 Flutter 登录 Twitter

flutter - 从多个Widget/State调用的通用类/函数

dart - 使用 dart 创建一个 javascript 库

java - Firestore 中是否有像 Firebase 中一样的 onChildAdded 方法?

java - 火力地堡 : updatePhoneNumber for Current User who logged in with google

Flutter firebase_messaging 后台处理程序不执行但消息到达 iOS

command-line - Windows 上的 Dart 命令行应用程序无法导入包