无法在Flutter应用中通过用户ID获取特定的用户文档

时间:2020-06-28 08:34:40

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

我想通过集合用户中的ID检索特定的用户文档。当我直接传递特定的用户ID时,我得到了数据。但是当我使用变量传递它时,它显示为空。

我的代码如下:

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

class test extends StatefulWidget {
  @override
  _testState createState() => _testState();

}
class _testState extends State<test> {

  String userID="";
  @override
  void initState() {
    super.initState();
    ///get current user and assign his id
    FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
      setState(() {
        userID = user.uid;
        print(userID);
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          StreamBuilder(
                  stream: Firestore.instance.collection('users').document(userID).snapshots(),
                  builder: (context,snapshot){
                    if (!snapshot.hasData) return const Text("Loading...");
                    else return Container(
                      child: Column(
                        children: <Widget>[
                          Text(snapshot.data["name"]),
                          Text(snapshot.data["email"]),
                          Text(snapshot.data["phone"].toString()),
                        ],
                      ),
                    );
                  },
                )
        ],
      )
    );
  }
}

当我使用下面的代码行并指定uid时,它会显示结果:

stream: Firestore.instance.collection('users').document('d6DshRomJMkIe9mAARAi').snapshots(),

但是当我在document()内部传递 userID 时,它不起作用。即使userID包含已登录用户的实际ID。

stream: Firestore.instance.collection('users').document(userID).snapshots(),

错误提示:

NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling []("name")

This is the structure of my database.

This is the error that I get on my app screen.

1 个答案:

答案 0 :(得分:3)

使用userID时不起作用,因为currentUser()是异步的,并且甚至在获取StreamBuilder之前就调用了userId,因此请尝试以下操作:

   Stream<DocumentSnapshot> getData()async*{
     FirebaseUser user = await FirebaseAuth.instance.currentUser();
     yield* Firestore.instance.collection('users').document(user.uid).snapshots();
  }

创建一个返回Stream的方法,然后在StreamBuilder内执行以下操作:

children: <Widget>[
          StreamBuilder(
                  stream: getData(),
                  builder: (context,snapshot){
                    if (!snapshot.hasData) return const Text("Loading...");
                    else if(snapshot.hasData){
                    return Container(
                      child: Column(
                        children: <Widget>[
                          Text(snapshot.data["name"]),
                          Text(snapshot.data["email"]),
                          Text(snapshot.data["phone"].toString()),
                        ],
                      ),
                    );
                   },
                return CircularProgressIndicator();
                  },
                )
        ],