如何从用户 ID 获取 Firestore 集合文档

时间:2021-04-23 12:25:09

标签: flutter google-cloud-firestore

我是 dart/flutter/firebase 的新手,无法弄清楚如何从 firestore 获取收集数据。下面说一个无效的集合路径。

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class UserProfile extends StatelessWidget {
  final String documentId = FirebaseAuth.instance.currentUser.uid;

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

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).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();
          return Text("Full Name: ${data['first_name']} ${data['last_name']}");
        }

        return Text("loading");
      },
    );
  }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,Firestore 安全规则不正确,因此此代码是正确的。