firebase - Firestore Flutter 中的 userId 为 null
问题描述
我想在我的 Firestore 中添加一个帖子,其中包含一些从应用程序中获取的值,比如帖子的标题和内容,并且它有效。但是,当我想获取发布该帖子的用户 ID 时,我会得到null。那么我该如何解决这个问题?另外,我可以获取用户名而不是 id 吗?我认为这样会更好。
这是代码:
onTap: () async {
if (_formkey.currentState.validate()) {
try {
setState(() {
_isSubmitting = true;
});
FirebaseAuth.instance.currentUser().then((user) {
userId = user.uid;
});
await Firestore.instance.collection("posts").document().setData({
'author': userId,
'title': _titleController.text,
'body': _bodyController.text,
'images': "empy for now",
'createdAt': FieldValue.serverTimestamp(),
});
解决方案
您没有在等待用户,因此在将 userId 设置为 user.uid 之前调用了 setData 函数
那是因为 .then 是异步的
要解决这个问题,我们必须先等待当前用户返回
onTap: () async {
if (_formkey.currentState.validate()) {
try {
setState(() {
_isSubmitting = true;
});
final user = await FirebaseAuth.instance.currentUser();
userId = user.uid;
await Firestore.instance.collection("posts").document().setData({
'author': userId,
'title': _titleController.text,
'body': _bodyController.text,
'images': "empy for now",
'createdAt': FieldValue.serverTimestamp(),
});
推荐阅读
- android - 用 Polygon 在整个地图上绘制一个矩形
- c# - 如何使用 get_range 方法 C# 使用变量?
- angularjs - 将 SPFx Web 部件添加到 SharePoint 经典页面会导致 PnP Widget Wrangler AngularJS 组件崩溃
- regex - 正则表达式:不仅是电子邮件中的数字
- r - Mac上Rstudio下的RWeka安装
- gensim - Spacy/Gensim - 创建相似的句子
- elixir - 关于调用模块内的宏
- messaging - 具有 SQS 订阅者持久性的 AWS SNS
- android - android错误:任务':app:transformClassesWithDexForRelease'的执行失败。
- image-processing - Python - 从图像中检索 3D 切片器和灰色和白色数据