如何从Flustore中检索当前用户信息

时间:2020-07-04 14:41:09

标签: firebase flutter dart google-cloud-firestore flutter-dependencies

下面的这段代码将检索集合中的所有信息,但是我只想检索当前的用户信息。我该怎么办?

class Booking extends State<BookingDetails> {
  final databaseReference = Firestore.instance;
  var firebaseUser = FirebaseAuth.instance.currentUser();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Appbar"),
      ),
      body: Center(
        child: Container(
            padding: const EdgeInsets.all(10.0),
            child: StreamBuilder<QuerySnapshot>(
              stream: Firestore.instance.collection('User1').snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasError)
                  return new Text('Error: ${snapshot.error}');
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return new Text('Loading...');
                  default:
                    return new ListView(
                      children: snapshot.data.documents
                          .map((DocumentSnapshot document) {
                        return new CustomCard(
                          title: document['name'],
                          description: document['phno'],
                        );
                      }).toList(),
                    );
                }
              },
            )),
      ),
    );
  }
}

我想为一个用户存储多个文档,我想从Firestore中检索并仅显示他的文档该怎么做?

1 个答案:

答案 0 :(得分:2)

如果要检索当前用户的信息,则在这种情况下,您必须检索一个文档。具有以下结构的示例:

User1 (collection) --> userID (document)

然后您需要执行以下操作:

 Stream<DocumentSnapshot> getData()async*{
     FirebaseUser user = await FirebaseAuth.instance.currentUser();
     yield* Firestore.instance.collection('User1').where("userId", isEqualTo: user.uid).snapshots();
  }

然后您可以做:

      body: Center(
        child: Container(
            padding: const EdgeInsets.all(10.0),
            child: StreamBuilder<QuerySnapshot>(
              stream: getData(),