如何解决“返回类型'DocumentReference()'不是方法所定义的'DocumentReference()'”错误?

时间:2019-03-28 08:11:18

标签: flutter google-cloud-firestore

我有3个功能,doesNameAlreadyExist检查文档是否存在。 我愿意对这些方法进行任何改进。

   Future<bool> doesNameAlreadyExist(String name) async {

      QuerySnapshot queryDb = await Firestore.instance
          .collection('locations')
          .where("city", isEqualTo: '${name}')
          .limit(1)
          .getDocuments();
      final List<DocumentSnapshot> documents = queryDb.documents;
      return documents.length == 1;
// I have to return DocumentReference if document is exists,
// Even though, it's not on the scope of this particular problem,
// I'm open to ideas. Maybe I can return a map, bool and reference combined


    }

此人将文档推送到Firestore。

    Future<DocumentReference> pushNameToFirestore(PlaceDetails pd) async {

      Future<DocumentReference> justAddedRef = Firestore.instance.collection('locations').add(<String, String>{
        'city': '${pd.name}',
        'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
      });
      return justAddedRef;
    }

在这里,我正在检查然后使用上面的那些功能。但是我无法返回文档参考。

    DocumentReference firestoreCheckAndPush() async {
     bool nameExists =  await doesNameAlreadyExist(placeDetail.name);
     // TODO notify user with snackbar and return reference
     DocumentReference locationDocumentRef;
     if(nameExists) {
       print('name exist');
     } else {
         locationDocumentRef = await pushNameToFirestore(placeDetail);
     }
        return locationDocumentRef; // Error is here
    }

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是您不等待自己的DocumentReference,因此您返回的是Future而不是实际期望的DocumentReference

尝试一下:

    Future<DocumentReference> pushNameToFirestore(PlaceDetails pd) async {

      DocumentReference justAddedRef = await Firestore.instance.collection('locations').add(<String, String>{
        'city': '${pd.name}',
        'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
      });
      return justAddedRef;
    }

这是一篇关于未来和异步的好文章:Link to the article

希望有帮助!!