Flutter + Firestore:类型'_InternalLinkedHashMap <String,dynamic>'不是类型'DocumentSnapshot'的子类型

时间:2020-04-13 12:40:18

标签: flutter dart google-cloud-firestore

我正在尝试将Firebase文档转换为类/模型。

首先,我运行一个查询:

  QuerySnapshot snapshot = await Firestore.instance
      .collectionGroup('myGroup')
      .where('letter', isEqualTo: 'a')
      .getDocuments();
  List results = [];

  snapshot.documents.forEach((f) {
    results.add(f.data);
  });

然后,我想将某个文档“转换”为类/模型。

我通常使用以下代码:

myResult = model.fromDocument(doc);

但是当我现在用此代码执行操作时:

myResult = model.fromDocument(results[3]);

出现此错误:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'DocumentSnapshot'

我看到了这个堆栈溢出的帖子:New: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'DocumentSnapshot'

问题是:如果您添加文档而不是document.data,它会起作用

snapshot.data[index].data // is of type Map<String,Dynamic>     
snapshot.data[index] // is the DocumentSnapshot

如何将doc.data转换为模型/类?

谢谢!

1 个答案:

答案 0 :(得分:0)

在执行doc.data时,您仅迈出了一步,即将其转换为模型,现在fromDocument中的旧转换看起来像

_songId = doc.data['songId'];

因为现在它的doc.data部分不见了,您只需要调用

_songId = data['songId'];//data is the value passed through fromDoc as parameter

或者您可以像这样简单地修改旧代码

List<DocumentSnapshot> results;

snapshot.documents.forEach((f) {
    results.add(f);//removing the .data
  });

//now this code below works just fine

myResult = model.fromDocument(results[3]);