0

I'm setting an User profile and I have a collection in my firestore which contain first 'users', in this I have the ID of this user and finally I can display name, uid etc. The problem is I want to print that name in my front end but I can't access this collection because I don't know how to use the current uid in my .doc(uid), (uid is undefined), I used a future method to get the uid but I don't know how to connect these. Hope you help me !

this is my frontend code

FutureBuilder(
              future: FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .get(), //tryna to use that collection but uid is not defined correctly 
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  var name = snapshot.data as DocumentSnapshot;
                  return Text(name['displayName'],
                  );
                } else {
                  return Text("Loading...");
                }
              },
            )

and my provider current User Id code

 Future<String> inputData()  async {
    final User? user =  _auth.currentUser;
    final uid = user!.uid;
    // here you write the codes to input the data into firestore
    return uid;
  }

I've updated frontend code here:

FutureBuilder(
              future: FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .get(), //tryna to use that collection but uid is not defined correctly and I need a void but
              // I have one in my auhtprovider
              //solution ? create id from here : use my provider
              builder: (context, snapshot) {
                if (snapshot.hasData)
                  return Text("Loading...");
                if (snapshot.data == null) {
                  print('Document does not exist on the database');
                }else{
                  return Text("Researching data...");
                }
                if (snapshot.connectionState == ConnectionState.done) {
                  var name = snapshot.data as DocumentSnapshot;
                  return Text(name['displayName'],
                  );
                } else {
                  return Text("Loading..");
                }
              },
            )

and UID ?

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future userSetup(String displayName) async {
  CollectionReference users = FirebaseFirestore.instance.collection('Users');
  FirebaseAuth auth = FirebaseAuth.instance;
  String uid = auth.currentUser!.uid.toString();
  await users.doc(uid).set({'displayName': displayName, 'uid': uid });
  final result = await users.doc(uid).get();
  final data = result.data() as Map<String, dynamic>;
  return data['displayName'];
}

Plus a photo of my firestore document :

enter image description here

  • 1
    `.doc(FirebaseAuth.instance.currentUser.uid)`? – Frank van Puffelen Aug 25 '21 at 20:24
  • I had to add "!" in `.doc(FirebaseAuth.instance.currentUser!.uid)` but it returns me the error : type 'Null' is not a subtype of type 'DocumentSnapshot' in type cast – kernelrpc_mach_vm_protect Aug 25 '21 at 20:46
  • So that sounds like there is no document for the current user, which you code doesn't handle. You'll need to check `if (snapshot.hasData)` before accessing `snapshot.data`, and then after that check if the document exists with `if (snapshot.data.exists)` before accessing `snapshot.data.data`. – Frank van Puffelen Aug 25 '21 at 20:50

1 Answers1

1

To use the current user's UID in the read operation, do:

.doc(FirebaseAuth.instance.currentUser.uid)

The error you get after that, makes it sound like there is no document for the current user, which you code doesn't handle.

You'll need to check if (snapshot.hasData) before accessing snapshot.data, to ensure the AsyncSnapshot is done communicating with the database.

Then after that check if the document exists with if (snapshot.data!.exists) before accessing snapshot.data!.data().

Note that is pretty much exactly what the code in the documentation on reading data once does, so I highly recommend checking that out (again if needed).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you I have no more errors except the fact that it returns to me 'Document does not exist on the database', I made a condition for more details you can check my code, I've updated – kernelrpc_mach_vm_protect Aug 25 '21 at 21:30
  • Please don't remove your existing code from the question, as it makes my answer meaningless for future visitors. If you want to show more code, show it as an addition to your existing code, not as a replacement. – Frank van Puffelen Aug 25 '21 at 21:48
  • 1) This looks like an inverted condition: `if (snapshot.hasData) return Text("Loading...");` 2) This `if (snapshot.data == null) {` looks like it should be `if (snapshot.data!.exists)`. 3) Can you show the UID that you used, and a screenshot of the document that you think should be loaded for that from the Firebase console. – Frank van Puffelen Aug 25 '21 at 22:01
  • I put ' == null ' because of that : The getter 'exists' isn't defined for the type 'Object'., and my uid ? It means the code for my firestore collection ? If it's the case I added to my post with a screen with the document which should be loaded. – kernelrpc_mach_vm_protect Aug 25 '21 at 22:25