簡體   English   中英

用戶 ID 是 Firestore Flutter 中的 null

[英]userId is null in Firestore Flutter

我想在我的 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 function

那是因為.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(),
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM