【问题标题】:Retrieving user's displayName and profile picture from Firebase从 Firebase 检索用户的 displayName 和个人资料图片
【发布时间】:2020-07-09 13:38:54
【问题描述】:

我正在做一个论坛移动应用程序,我想在用户上传帖子时显示用户的个人资料图片和用户名。我已将一个 ownerid 字段(即发帖人的 uid)与帖子详细信息一起存储到 Firebase 中。使用 uid,我如何访问用户的显示名和头像?

这是我的帖子类:

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

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,)],)
                ],)
      ),),)
            );
    }

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    除了控制台之外,您无法直接访问所有通过 Firebase 身份验证的用户。

    一种解决方法是拥有一个users 集合,您将在其中存储注册后需要的所有用户信息。由于您从帖子中获得了用户 ID,因此将其用作 users 集合中每个用户的文档 ID 会更容易。然后,您可以使用帖子中的用户 ID 从 users 集合中获取他的文档,该集合将包含他的所有详细信息。

    【讨论】:

    • 我确实有一个用户的集合,每个 documentid 都是用户的 uid,每个文档都有一个名为 username 的字段。如何访问用户名字段?
    【解决方案2】:

    假设您已经在 firebase 中有一个名为“users”的集合,您在其中存储登录时的用户数据。还有一个名为“uid”的字段,您将在其中存储 uid

    在firebase中检查具有相同uid的用户并提取详细信息

    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;
    
    

    为了保存读取,我建议使用用户的 uid 命名“用户”集合的文档 ID,因为在这种情况下,您可以进行直接查询,例如

     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"
    

    【讨论】:

    • 感谢您的帮助!我使用 futurebuilder 来显示用户名。然而,它不断地给出圆形进度指示器标志。它有什么问题吗?我已将代码包含在问题中。
    【解决方案3】:

    你好,我遇到了同样的问题,因为我使用的是最近的颤振版本,我的解决方案是: 我在 Build 上下文中创建了一个 var 来获取用户 iD firdt,然后我在 FutureBuilder 中调用它来访问用户名,然后创建一个 var ownwerId 并在构造函数中接受它,然后你可以对另一个 FutureBuilder 做同样的事情,它对我有用,对你也有用:

     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();}
        }, 
     ),
    

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 2017-05-04
      • 2021-01-15
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      相关资源
      最近更新 更多