无法将数据添加到Firestore数据库。

huangapple go评论56阅读模式
英文:

Unable to add data to Firestore Database

问题

I am trying to put user info to Firestore Database, but this is not working as I expected.

我正在尝试将用户信息存入Firestore数据库,但这并不如我所期望的那样工作。

I installed required packages including cloud_firestore.

我安装了必需的包,包括cloud_firestore。

I used this code for adding users data to the database.

我使用了以下代码将用户数据添加到数据库中。

try {
setState(() {
_isEntering = true;
});
if (_isLogin) {
var userCredentials = await _firebase.signInWithEmailAndPassword(
email: _enteredEmail, password: _enteredPassword);
} else {
var userCredentials = await _firebase.createUserWithEmailAndPassword(
email: _enteredEmail, password: _enteredPassword);
var storageRef = FirebaseStorage.instance
.ref()
.child("profile_images")
.child("${userCredentials.user!.uid}.jpg");
storageRef.putFile(_selectedImage!);
var profileImageUrl = await storageRef.getDownloadURL();

FirebaseFirestore.instance.collection("users").doc(userCredentials.user!.uid).set({
   "username":"将被赋予..",
   "email":_enteredEmail,
   "profile_image_url":profileImageUrl
 });

}
} on FirebaseAuthException catch (e) {
if (e.code == "email-already-in-use") {}
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(e.message ?? "Authentication failed"),
),
);
setState(() {
_isEntering = false;
});
}

Also, I tried to use the same approach as said on the official Firestore website. text

此外,我尝试使用与官方Firestore网站上所说的相同方法。文本

var db = FirebaseFirestore.instance;

var db = FirebaseFirestore.instance;

final user = <String, dynamic>{
"username":"将被赋予..",
"email":_enteredEmail,
"profile_image_url":profileImageUrl
};

// Add a new document with a generated ID
// 使用生成的ID添加新文档
db.collection("users").add(user).then((DocumentReference doc) =>
print('DocumentSnapshot added with ID: ${doc.id}));

我不确定是什么原因导致了这个问题。
我查看了一些部分相同问题的问题。
enter link description here
但原因仍然未知。
如果有人知道,请帮助我使其工作。

我不确定是什么原因导致了这个问题。
我查看了一些部分相同问题的问题。
enter link description here
但原因仍然未知。
如果有人知道,请帮助我使其工作。

英文:

I am trying to put user info to Firestore Database, but it this is not working as I expected.

I installed required packages including cloud_firestore.

I used this code for adding users data to database.

try {
  setState(() {
    _isEntering = true;
  });
  if (_isLogin) {
    var userCredentials = await _firebase.signInWithEmailAndPassword(
        email: _enteredEmail, password: _enteredPassword);
  } else {
    var userCredentials = await _firebase.createUserWithEmailAndPassword(
        email: _enteredEmail, password: _enteredPassword);
    var storageRef = FirebaseStorage.instance
        .ref()
        .child(&quot;profile_images&quot;)
        .child(&quot;${userCredentials.user!.uid}.jpg&quot;);
    storageRef.putFile(_selectedImage!);
    var profileImageUrl = await storageRef.getDownloadURL();

    FirebaseFirestore.instance.collection(&quot;users&quot;).doc(userCredentials.user!.uid).set({
       &quot;username&quot;:&quot;will be given..&quot;,
       &quot;email&quot;:_enteredEmail,
       &quot;profile_image_url&quot;:profileImageUrl
     });


  }
} on FirebaseAuthException catch (e) {
  if (e.code == &quot;email-already-in-use&quot;) {}
  ScaffoldMessenger.of(context).clearSnackBars();
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(e.message ?? &quot;Authentication failed&quot;),
    ),
  );
  setState(() {
    _isEntering = false;
  });
}

Also, I tried to use the same approach as said in official Firestore wesite. text

    var db = FirebaseFirestore.instance;


    final user = &lt;String, dynamic&gt;{
      &quot;username&quot;:&quot;will be given..&quot;,
       &quot;email&quot;:_enteredEmail,
       &quot;profile_image_url&quot;:profileImageUrl
    };

    // Add a new document with a generated ID
    db.collection(&quot;users&quot;).add(user).then((DocumentReference doc) =&gt;
        print(&#39;DocumentSnapshot added with ID: ${doc.id}&#39;));
  }

I am not sure what is causing to this problem.
I have looked some questions which have partially same problems.
enter link description here
But again the reason is still unknown.
If anyone knows something please help to make it work.

答案1

得分: 1

好的,以下是翻译好的内容:

最终,我发现了问题。在我的项目中,当我将我的个人资料图片添加到Firebase存储时,我意识到我忘记在putFile操作之前包含await关键字。这个错误阻止了代码正确上传图片到存储。

var userCredentials = await _firebase.createUserWithEmailAndPassword(
            email: _enteredEmail, password: _enteredPassword);

var storageRef = FirebaseStorage.instance
    .ref()
    .child("profile_images")
    .child("${userCredentials.user!.uid}.jpg");
await storageRef.putFile(_selectedImage!);

var profileImageUrl = await storageRef.getDownloadURL();

通过在调用putFile时使用await,代码将在转到下一行之前等待上传操作完成。

英文:

Finally, I discovered the issue. In my project, when I was adding my profile image to Firebase Storage, I realized that I forgot to include the await keyword before the putFile operation. This mistake prevented the code from properly uploading the image to the storage.

    var userCredentials = await _firebase.createUserWithEmailAndPassword(
                email: _enteredEmail, password: _enteredPassword);

    var storageRef = FirebaseStorage.instance
        .ref()
        .child(&quot;profile_images&quot;)
        .child(&quot;${userCredentials.user!.uid}.jpg&quot;);
    storageRef.putFile(_selectedImage!);

    var profileImageUrl = await storageRef.getDownloadURL();

Updated code:
var userCredentials = await _firebase.createUserWithEmailAndPassword(
email: _enteredEmail, password: _enteredPassword);

    var storageRef = FirebaseStorage.instance
        .ref()
        .child(&quot;profile_images&quot;)
        .child(&quot;${userCredentials.user!.uid}.jpg&quot;);
    await storageRef.putFile(_selectedImage!);

    var profileImageUrl = await storageRef.getDownloadURL();

By using await when calling putFile, the code will wait for the upload operation to complete before moving to the next line.

huangapple
  • 本文由 发表于 2023年7月6日 20:35:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定