juliarobins
juliarobins

Reputation: 11

Retrieving user's displayName and profile picture from Firebase

I am doing a forum mobile application and l would like to display the user's profile picture and username when they upload a post. I have stored an ownerid field (which is uid of person who posted) along with the post details into Firebase. With the uid, how do I access the user's displayname and profile picture?

This is my post class:

class Post { //for forums


String title;
  String content;
  String timestamp;
  String imageurl;
  String username;
  String profilePicture;
  String documentid;
  String ownerid;
  Map<String, dynamic> saved = {};
  Map<String, dynamic> upvotes = {};
  


  Post(
    this.title,
    this.content,
    this.timestamp,
    this.imageurl,
    this.username,
    this.profilePicture,
    this.documentid,
    this.ownerid,
    this.saved,
    this.upvotes
    //this.image
  );

  Post.fromSnapshot(DocumentSnapshot snapshot) : 
  title = snapshot["title"],
  content = snapshot['content'],
  timestamp = snapshot['timestamp'],
  imageurl = snapshot['imageurl'],
  username = snapshot['username'],
  profilePicture = snapshot['profilePicture'],
  documentid = snapshot['documentid'],
  upvotes = snapshot['upvotes'],
  ownerid = snapshot['ownerid'],
  saved = snapshot['saved'];
}


FutureBuilder( 
              future: Firestore.instance.collection('users').document(post['ownerid']).get(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Text(snapshot.data['username'], style: TextStyle(fontWeight: FontWeight.bold,
                      fontSize: 16, decoration: TextDecoration.underline, color: Colors.grey[100]),
                   );
                } else {
                  return CircularProgressIndicator();
                }
              }, 
          ),

//Future builder is used in here

Widget buildForum(BuildContext context, DocumentSnapshot post) {
    final forum = Post.fromSnapshot(post);
    
    return Container(
      child: Card(
        color: Colors.grey[850],
        shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(18.0)),
        child: InkWell(
          onTap: () {
            Navigator.push(context, MaterialPageRoute(
              builder: (context) => ForumDetails(forum: forum) //with this particular forum 
            ));
          },
      child: Padding(
        padding: EdgeInsets.only(top: 4, bottom: 4),
                child: Column(
                  children: <Widget>[
                    Padding(
                    padding: EdgeInsets.only(top: 4, bottom: 8),
                    child:
                    Row(children: <Widget>[
                      SizedBox(width: 10,),
                      Text('Uploaded on ', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold,
                      color: Colors.grey[400]),),
                      Text(post['timestamp'], 
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold,
                      color: Colors.grey[400]),),
                      Spacer(),   
                    ],),
                    ),
                    SizedBox(height: 10),
                    Row(children: <Widget>[
                      SizedBox(width: 10,),
                      CircleAvatar(
                      backgroundImage: post['profilePicture'] != null ?
                      NetworkImage(post['profilePicture']) : 
                      NetworkImage('https://genslerzudansdentistry.com/wp-content/uploads/2015/11/anonymous-user.png'),
                      backgroundColor: Colors.grey,
                      radius: 20,),
                      SizedBox(width: 10,),
                      //post['ownerid']
                    //   Text(post['username'], style: TextStyle(fontWeight: FontWeight.bold,
                    //   fontSize: 16, decoration: TextDecoration.underline, color: Colors.grey[100]),
                    // ),
               FutureBuilder( 
              future: Firestore.instance.collection('users').document(post['ownerid']).get(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Text(snapshot.data['username'], style: TextStyle(fontWeight: FontWeight.bold,
                      fontSize: 16, decoration: TextDecoration.underline, color: Colors.grey[100]),
                   );
                } else {
                  return CircularProgressIndicator();
                }
              }, 
          ),
                    
                    ],),
                    SizedBox(height: 10),
                    Padding( 
                    padding: EdgeInsets.only(top: 4, bottom: 8),
                    child:
                    Row(children: <Widget>[
                      SizedBox(width: 10,), 
                      Expanded(child:
                      Text(post['title'], style: TextStyle(fontSize: 18,
                      fontWeight:FontWeight.bold, color: Colors.grey[100]))),
                    ],)),
                    //display image if there is
                    (post['imageurl'] != null)  ?
                    Padding( 
                    padding: EdgeInsets.only(top: 4, bottom: 8),
                    child:
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                      SizedBox(width: 10,), 
                      ClipRRect(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(8.0),
                      topRight: Radius.circular(8.0),
                      ),
                      child:  Image.network(post['imageurl']),
                      ),
                      //image of notes
                    ],),) : Container(height:0),
                    Padding(
                    padding: EdgeInsets.only(top: 4, bottom: 8),
                    child:
                    Row(children: <Widget>[
                      SizedBox(width: 10,),
                      Expanded(child:
                      Text(post['content'], style: TextStyle(fontSize: 16, color: Colors.grey[100]),
                      overflow: TextOverflow.ellipsis, maxLines: 2,),),
                    ],)),
                    SizedBox(height: 20),
                    Row(children: <Widget>[
                      SizedBox(width: 10,),
                      Icon(Icons.comment, size: 26,
                      color: Colors.tealAccent),
                       SizedBox(width: 6,),
                       Text('0', style: TextStyle(color: Colors.grey[100]),), //change to icons
                      Spacer(),
                      Icon(Icons.thumb_up, size: 26, color: Colors.tealAccent),
                      SizedBox(width: 6,),Text(post['upvotes'].values.where((e)=> e as bool).length.toString(), style: TextStyle(color: Colors.grey[100]),),
                    SizedBox(width: 10,)],)
                ],)
      ),),)
            );
    }

Upvotes: 0

Views: 978

Answers (3)

Neo
Neo

Reputation: 1

hello fella I was having the same problem since im using the recent flutter version my solution was: I created a var in the Build context to get user iD firdt, then I called it in the FutureBuilder to access the username, then create a var ownwerId and accept it in the constractor then you can just do the same thing for the other FutureBuilder, it worked for me it does to you as well:

 classname/constructorname (this.ownerId);

final string ownwerId;

 @override
  Widget build(BuildContext context) {
 CollectionReference users= FirebaseFirestore.instance.collection('users');

...
FutureBuilder( //create a var ownwerId and accept it in the constractor
        future: users.doc(ownerid).get(),
      builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                       
 if (snapshot.connectionState == ConnectionState.done) {

Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text(
data['username'], 
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 16, 
decoration: TextDecoration.underline, 
color: Colors.grey[100]),);
} else {return CircularProgressIndicator();}
    }, 
 ),

Upvotes: 0

Abdul Malik
Abdul Malik

Reputation: 1188

Assuming you already have a collection in firebase named "users" where you are storing user data on login. And there is a field named "uid" in which you are storing the uid

Check for the user with the same uid in firebase and extract the details

QuerySnapshot snapshot = awaitFirestore.instance.collection("users").where("uid",isEqualTo:ownerId).getDocuments()

//if you are sure that there is exactly one user with the same uid
Map<String,dynamic> userInfo = snapshot.documents[0].data;

To save reads i'd suggest naming the document Ids of the "users" collection with the uid of the user, because in that case you can make a straight forward query such as

 DocumentSnapshot doc = await Firestore.instance.collection("users").document(ownerId).get();

//To access any fields on the document retrieved
String username = doc.data["username"] //assuming the fields name in the document 
                                       //is "username"

Upvotes: 1

Akora Ing. DKB
Akora Ing. DKB

Reputation: 1051

You don't have direct access to all firebase authenticated users except from the console.

A workaround will be to have a users collection which you will store all the user information you will need after registration. Since you have the user's id from the post, it'll be easier to use that as the document id for each user in the users collection. Then you can use the user id from the post to get his document from the users collection which will contain all his details.

Upvotes: 1

Related Questions