首页 > 解决方案 > 颤动 | 如何检查文件是否存在于firestore中

问题描述

在这里我想检查一个文档是否存在于firestore中,如果存在它应该执行'if'部分否则'else'部分,我使用的文档ID与用户ID相同,这是我到目前为止得到的:

    class MapScreenState extends State<DashboardPage> {
      FirebaseUser user;
    
      Stream<DocumentSnapshot> getData() async*{
        user = await FirebaseAuth.instance.currentUser();
        yield* Firestore.instance.collection('Profile').document(user.uid).snapshots();
      }
    
      bool present = false;
    
      checkIfPresentOrNot() async{
        DocumentSnapshot ds = await Firestore.instance.collection("Profile").document(user.uid).get();
        this.setState(() {
          present = ds.exists;
        });
      }
    
      @override
      void initState() {
        super.initState();
        checkIfPresentOrNot();
        getData();
      }
  @override
  Widget build(BuildContext context) {

    return StreamBuilder(
      stream: getData(),
      builder: (context, snapshot) {
        if (present) {
          var userDocument = snapshot.data;
           return new showProfile(
            name: userDocument['name'],
            email: userDocument['email'],
            pin: userDocument['pin'],
            address: userDocument['address'],
          );
        }else{
         return new showProfile(
           name: "",
           email: "",
           pin: "",
           address: "",
         );
        }
      },
    );
  }
}

但是,当我运行此代码时,即使文档存在于 firestore 中,也只会执行 else 部分。我该如何解决这个问题?

标签: firebasefluttergoogle-cloud-firestore

解决方案


推荐阅读