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

问题描述 投票:0回答:1

我有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
    }
flutter google-cloud-firestore
1个回答
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

希望它的帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.