Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving Day to Firestore for the first time only in flutter

After registering as a member of firebase, you are also trying to add data to the firestore
The code is as follows

await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).set({
        '1_email' : FirebaseAuth.instance.currentUser!.email,
        '2_name' : 'Null',
        '3_phone' : '01012345678',
        '4_age' : 20,
        }
      );

I want the data to be stored in the firestore only for the first time
So I tried to code it as follows, but I couldn’t solve it

if(FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid) == null){
      await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).set({
        '1_email' : FirebaseAuth.instance.currentUser!.email,
        '2_name' : 'Null',
        '3_phone' : '01012345678',
        '4_age' : 20,
        }
      );
    }

What I thought was that if a document such as user uid is null in the fireestore, I added data, and if it is not null, I wrote a code in the form of leaving it alone, but I couldn’t solve it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line is meaningless:

if(FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid) == null){

You’re checking whether a document reference is null, which is will never be. What you want to do, is check whether the document exists, for which you will have to try and read it from the database.

var ref = FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid);
var snapshot = await ref.get();
if(!snapshot.exists){
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading