首页 > 解决方案 > 为什么我不能在 Flutter 中更新 Firestore 字符串值?

问题描述

我有一个按钮,当我按下它时,我希望它用一个字符串更新一个空值。在代码中,您会注意到一个未来的构建器,并且只知道我需要它来确定我应该根据 Firestore 中的数据状态准确更新什么。创建用户时,其值isPledged设置为 null,但正如您在 if 语句中看到的那样,如果该值为 null,我想用字符串“true”更新它。但是,当我这样做时,Firestore 中没有任何变化,其值仍为 null。我对我搞砸的地方有点困惑,所以任何帮助都将不胜感激。另外,我知道我可以删除 if 语句,但如果值确实有数据,我将添加另一个选项,所以这就是存在的原因。

onPressed: () {
  FutureBuilder(
    future: getPledgedStatus(),
    builder: (_, AsyncSnapshot snapshot) {
    if (!snapshot.hasData) {
      final CollectionReference
      users = FirebaseFirestore.instance.collection('UserNames');
      FirebaseAuth auth = FirebaseAuth.instance;
      String uid = auth.currentUser.uid.toString();
      users.doc(uid).update(
        {'isPledged': "true"}
      );
    }

    },
  );
  Navigator.of(context).pop();
},

标签: firebasefluttergoogle-cloud-firestore

解决方案


好的,所以在 Muthu Thavamani 提醒我可以简单地使用 async 函数而不是它工作的未来构建器之后,这是新代码:

onPressed: () async {
  try {
    final CollectionReference users = firestore.collection('UserNames');
    final String uid = auth.currentUser.uid;
    final result = await users.doc(uid).get();

    var isPledged = result.data()['isPledged'];

    if (isPledged == null) {
      FirebaseFirestore.instance.collection('UserNames').doc(uid).update({
        "isPledged": "true",
      });
      Navigator.of(context).pop();
    } else {
      //Something else
    }
  } catch (e) {
    print(e);
  }
}

推荐阅读