首页 > 解决方案 > 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(),
          });

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


您没有在等待用户,因此在将 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(),
      });

推荐阅读