skip to Main Content

I want to acess the uname field of the current loggedin user .
I added uname in the registration screen like this :

 onPressed: () async {
                    try {
                      final newuser = await FirebaseAuth.instance
                          .createUserWithEmailAndPassword(
                        email: email ?? 'error',
                        password: password ?? 'error',
                      );
                      await FirebaseFirestore.instance
                          .collection('Users')
                          .add({' uname': username});

                      if (newuser != null) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => home()),
                        );
                      }
                    } catch (e) {
                      print(e);
                    }
                  }

But I dont know how to acess it from another file or more specifically I want to acess it on the profile screen .

How can I acess the uname field from firestore in flutter?

cloudconsole

2

Answers


  1. I think the better way to what you want is to set the document ID in the collection("Users") same as the uid of the user authenticated. So fetching details or in this case, uname will be easier.

    For creating doc with docID same as user uid:

    await FirebaseFirestore.instance
        .collection('Users')
        .doc(newUser.uid)
        .add({' uname': username});
    

    For fetching details:

    final userData = await FirebaseFirestore.instance
        .collection("Users")
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .get();
    
    Login or Signup to reply.
  2. You should call the document in the initState and set the value of string using setState

    Code:

    class ProfileScreen extends StatefulWidget {
      const ProfileScreen({super.key});
    
      @override
      State<ProfileScreen> createState() => _ProfileScreenState();
    }
    
    class _ProfileScreenState extends State<ProfileScreen> {
      String? name;
    
      @override
      void initState() {
        FirebaseFirestore.instance
            .collection('Users')
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .get()
            .then((value) {
          print(value.data()?[' uname'];
          setState(() {
            name = value.data()?[' uname'];
          });
        });
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
              child:
                  name != null ? Text(name!) : const CircularProgressIndicator()),
        );
      }
    }
    

    Note: This is not recommended ⚠

    As future method is called inside the initState(){} it is heavily discouraged to do so as it slows down the process of building the widget and also not considered as a good practice.

    Use FutureBuilder for this:

     @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
              child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
            future: FirebaseFirestore.instance
                .collection('users')
                .doc(FirebaseAuth.instance.currentUser!.uid)  
                .get(),
            builder: (_, snapshot) {
              if (snapshot.hasError) return Text('Error = ${snapshot.error}');
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
              }
              Map<String, dynamic> data = snapshot.data!.data()!;
              return Text(data['fullName']); //👈 Your valid data here
            },
          )),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search