首页 > 解决方案 > 如何“等待”非未来变量?

问题描述

DocumentReference locationDocumentRef;在我的状态。

我正在locationDocumentRef根据参考资料进行更改,无论是通过查询还是通过添加新文档来收集。

所以我有这个功能来检查文档,如果有一个设置它对 . 的引用locationDocumentRef,或者添加一个新的并将它的 ref 设置为locationDocumentRef. 我每次都通过将其设置为 null 来重置它的值,因为我不想获得以前的结果。但它打印空。

所以我的问题是,我怎样才能解决它们并获得价值?我认为我在代码中解决得太早了,所以我不能等待一个非未来的值。我该如何解决?

void firestoreCheckAndPush() async {
  setState(() {
    locationDocumentRef = null;
  });
  bool nameExists = await doesNameAlreadyExist(placeDetail.name);
  if (nameExists) {
    print('name exist');
  } else {
    print('name will be pushed on firestore');
    pushNameToFirestore(placeDetail);
  }
  var resolvedRef = await locationDocumentRef;
  print(resolvedRef.documentID); // I get null here
}

这些是我使用过的功能

Future<bool> doesNameAlreadyExist(String name) async {
      QuerySnapshot queryDb = await Firestore.instance
          .collection('locations')
          .where("city", isEqualTo: '${name}')
          .limit(1)
          .getDocuments();

      if (queryDb.documents.length == 1) {
        setState(() {
          locationDocumentRef = queryDb.documents[0].reference;
        });
        return true;
      } else {
        return false;
      }
    }

和另一个

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

标签: dartflutterasync-awaitgoogle-cloud-firestore

解决方案


我首先在这里看到了两个错误 var resolvedRef = await locationDocumentRef; 为什么你等待 locationDocumentRef,其次你不等待 pushNameToFirestore(PlaceDetails pd) firestoreCheckAndPush() 函数,这很奇怪,因为 pushNameToFirestore(String) 是同步的,这意味着你不会等待它完成,所以如果你要添加一个新名称,它会打印空。如果我错了,请纠正我。您可以在此处找到有关同步和未来的更多信息https://www.dartlang.org/tutorials/language/futures 查看页面中间的图表


推荐阅读