firebase - 为什么我不能在 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();
},
解决方案
好的,所以在 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);
}
}
推荐阅读
- reactjs - 如何处理具有对象属性的数组以生成反应元素
- javascript - 里程表无法仅在 OBS 中加载
- spring-boot - Spring Boot 应用程序的 docker 镜像
- java - Java 通用列表 - 使用 Array.newInstance 导致 Nullpointer
- r - 获取有向图的所有组合组合
- typo3-9.x - 电子邮件标题修改以避免 Typo 3 中的垃圾邮件(电源邮件扩展)
- raspberry-pi - 树莓派 3 第一次重启后没有网络
- thymeleaf - 通过外部循环的 id 过滤对象 int 循环的列表
- c# - 用另一个字符串拆分一个字符串,除了
- sql - 从多个表中选择,不直接连接