【问题标题】:Flutter Firestore - Show a specific document with all the values it hasFlutter Firestore - 显示具有所有值的特定文档
【发布时间】:2020-10-05 22:09:02
【问题描述】:

当用户转到个人资料页面查看他们自己的信息时,我一直在尝试显示文档。到目前为止我所做的是:

  class Profile extends StatefulWidget {

  Profile({Key key}) : super(key: key);

  @override
  _ProfileState createState() => _ProfileState();

}

class _ProfileState extends State<Profile> {

  Firestore _firestore = Firestore.instance;
  List<DocumentSnapshot> _members = [];

  bool _loading = true;

  _getMember() async {
    var firebaseUser = await FirebaseAuth.instance.currentUser();
   Query query = _firestore.collection("membership");
    setState(() {
      _loading = true;
    });
   QuerySnapshot querySnapshot = await query.getDocuments();
   _members = querySnapshot.documents;
     setState(() {
     _loading = false;
   });
  }

  @override
  void initState() {
    super.initState();
    _getMember();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Profile"),
      ),
      body: Container(
        child: _members.length == 0 ? Center(child: Text("empty"),) : ListView.builder(
            itemCount: _members.length,
            itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(_members[index].data["name"]),
          );
        }),
      ),
    );
  }
}

但这仅显示名称。此外,它还显示了我不希望发生的来自同一集合的另一个文档。

My collection:

我的问题是: 如何获取具有文档中所有值的特定文档的数据? 具体顺序,例如:

姓名:gün

姓氏:乌鲁特库

年龄:59

体重:90

电话号码:+05075326895

注意:我使用用户 ID 作为文档 ID。

【问题讨论】:

  • sry,但这不是很明显吗?您可以像使用“名称”一样进行操作,因此对于姓氏,它的 _members[index].data["surname"] 等等。要访问特定文档,请使用final DocumentReference docRef = _firestore.collection("membership").document("userId");,而不是查询整个集合。

标签: firebase flutter google-cloud-firestore


【解决方案1】:

正如评论中所指出的,您必须沿着通往 Document 的路径,而不是仅仅查询整个 Collection 以从用户那里收集信息。这是一个如何使用用户 ID 检索文档的示例:

  void _onPressed() async{
    var firebaseUser = await FirebaseAuth.instance.currentUser();
    firestoreInstance.collection("users").document(firebaseUser.uid).get().then((value){
      print(value.data);
    });
  }

你可以从here找到更多的例子

【讨论】:

  • 我要求从 Firestore 中检索数据,而不是向 Firestore 添加数据。
  • 对不起,我复制了错误的代码,我编辑了帖子以反映正确的代码。但所有这些都来自我的答案中链接的页面。
  • 在写到这里之前我已经看过那个链接了。它没有帮助我。也许我不明白它的逻辑或者它不是我的代码,我不知道。
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 2020-11-20
  • 2018-04-06
  • 2022-11-22
  • 1970-01-01
  • 2021-08-25
  • 2020-02-24
  • 2019-08-15
相关资源
最近更新 更多