Showing all user data, Want to show just logged user data in my profile section

Issue

I want to show my crrentUser/logged In user data to my profile in a Drawer when I will slide it, will show the current/login user ‘name, email, photos’ there will be some another thing like logout button etc. But when I logged with any user in that user dashboard. when I click/slide on my Drawer it shows all the users data which I stored in my Firestore under users collection. I just want to show the Current user profile data like name email etc. But it shows all the collection from the Firestore. Currently, I have 3 users in my users collections in my firebase. The problem is when I slide/click the Drawer it shows all 3users data in my Drawer. But i just want to show only current/login user data in my Drawer

import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../screens/user_product_list_view.dart';

class UserDrawer extends StatefulWidget {
  UserDrawer({Key? key}) : super(key: key);

  @override
  _UserDrawerState createState() => _UserDrawerState();
}

class _UserDrawerState extends State<UserDrawer> {
  @override
  void initState() {
    super.initState();
    getUser();
  }

  Future getUser() async {
    var currentUserLoginUser = await FirebaseAuth.instance.currentUser;
    var firebaseUser = await FirebaseFirestore.instance
        .collection('users')
        .doc(currentUserLoginUser!.uid);
    print(currentUserLoginUser.email);
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: SafeArea(
        child: Scaffold(
          backgroundColor: Theme.of(context).primaryColor,
          body: StreamBuilder(
            stream: FirebaseFirestore.instance.collection('users').snapshots(),
            builder: (BuildContext contex,
                AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
              if (!snapshot.hasData) {
                return Text('User is not found');
              }
              return ListView(
                children: snapshot.data!.docs.map(
                  (document) {
                    return Stack(
                      children: [
                       ///
                        Container(
                          padding: EdgeInsets.only(top: 105),
                          height: 300,
                          width: double.infinity,
                          decoration: BoxDecoration(
                              color: Theme.of(context).primaryColorDark,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(120))),
                          child: Column(
                            children: [
                              CircleAvatar(
                                radius: 40,
                                backgroundColor: Colors.blueAccent,
                              ),
                              Text(
                                document['email'],
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 20),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 20, vertical: 10),
                          height: 100,
                          width: double.infinity,
                          child: Text(
                            'Profile',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          decoration: BoxDecoration(
                              color: Theme.of(context).primaryColorLight,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(80))),
                        ),
                      ],
                    );
                  },
                ).toList(),
              );
            },
          ),
        ),
      ),
    );
  }
}

Like currently, I am login as dolon@gmail.com I Just want to show the login user Email and name .other two will not appear here.  when I will log in to another account it will show that account email and name

This is my Firestore collection I want to show a specific user information in my profile which I created on my drawer

Solution

So I think the problem was with steamBuider which I am assuming. I think SteamBuilder print everything in a collection. As I need to print only my current/login user by using SreamBuilder it’s fetching all document data from users collections that’s why the problem was occurring.
Now I changed to FutureBuilder and is perfectly working now.
**I am not sure about what was the problem with StreamBuilder but If I need the whole collection then I will use SteamBuilder else if I need just a specific document under a Collection then i will use FutureBuilder.

That’s my opinion if anyone can give some idea that will be very helpful

import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../screens/user_product_list_view.dart';

class UserDrawer extends StatefulWidget {
  UserDrawer({Key? key}) : super(key: key);

  @override
  _UserDrawerState createState() => _UserDrawerState();
}

class _UserDrawerState extends State<UserDrawer> {
  @override
  void initState() {
    super.initState();
    getUser();
  }

  var currentUserLoginUser = FirebaseAuth.instance.currentUser;
  Future getUser() async {
    var currentUserLoginUser = await FirebaseAuth.instance.currentUser;
    var firebaseUser = await FirebaseFirestore.instance
        .collection('users')
        .doc(currentUserLoginUser!.uid);
    print(currentUserLoginUser.email);
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: SafeArea(
        child: Scaffold(
          backgroundColor: Theme.of(context).primaryColor,
          body: FutureBuilder<DocumentSnapshot>(
            future: FirebaseFirestore.instance
                .collection('users')
                .doc(currentUserLoginUser!.uid)
                .get(),
            builder: (BuildContext context,
                AsyncSnapshot<DocumentSnapshot> snapshot) {
              if (snapshot.hasError) {
                return Text("Something went wrong");
              }
              if (snapshot.hasData && !snapshot.data!.exists) {
                return Text("Document does not exist");
              }
              if (snapshot.connectionState == ConnectionState.done) {
                Map<String, dynamic> data =
                    snapshot.data!.data() as Map<String, dynamic>;
                return Stack(
                  children: [
                    Container(
                      padding: EdgeInsets.only(top: 600),
                      decoration: BoxDecoration(
                          color: Theme.of(context).primaryColorLight,
                          borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(80))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ElevatedButton(
                              onPressed: () {
                               FirebaseAuth.instance.signOut();
                              },
                              child: Text('Logout')),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 400),
                      decoration: BoxDecoration(
                          color: Theme.of(context).primaryColorLight,
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(80))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                              child: ElevatedButton(
                                  onPressed: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                UserProductList()));
                                  },
                                  child: Text('My Products'))),
                          SizedBox(
                            width: 08,
                          ),
                          Expanded(
                              child: ElevatedButton(
                                  onPressed: () {}, child: Text('data'))),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(top: 105),
                      height: 300,
                      width: double.infinity,
                      decoration: BoxDecoration(
                          color: Theme.of(context).primaryColorDark,
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(120))),
                      child: Column(
                        children: [
                          CircleAvatar(
                            radius: 40,
                            backgroundColor: Colors.blueAccent,
                          ),
                          Text(
                            ' Name: ${data['username']} ',
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                      height: 100,
                      width: double.infinity,
                      child: Text(
                        'Profile',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      decoration: BoxDecoration(
                          color: Theme.of(context).primaryColorLight,
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(80))),
                    ),
                  ],
                );
              }
              return Text('Loading');
            },
          ),
        ),
      ),
    );
  }
}

Answered By – Md. Fazle Rabbi

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *