如何通过对 uid 的异步调用从 Firebase 查询数据

How to query data from Firebase with an async call to uid

我正在尝试获取属于已登录用户的数据,但是,由于某种原因,"getuserui" 是异步的。即使用户已登录以在应用程序内部执行操作,该功能仍然 returns 一个 Future....

我已经记不清自己尝试了多少不同的东西,包括 .then 等等,但这是我最近的尝试。

 @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 900,
      child: StreamBuilder(
          stream: () async{
            fireFirestore.instance.collection('properties').where('uid', isEqualTo: await _authService.getUserId()) .snapshots(),
          }, 
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData)
              return const Text('Loading...');
            else {
              return ListView.builder( ...............

如果您需要查看 getUserId():

Future<String> getUserId() {
    return _auth.currentUser().then((value) => value.uid.toString());
  }

(我已经在未来的方式 (.then) 和异步方式 (async await) 中完成了这个方法

它只是告诉我 the argument type Future<null> can't be assigned to the parameter type Stream

首先,您将异步函数作为流传递,因此会出现错误。其次,您需要将 StreamBuilder 包装在 FutureBuilder 中,因为它取决于未来 _authService.getUserId().

@override
Widget build(BuildContext context) {
  return SizedBox(
    height: 900,
    child: FutureBuilder(
      future: _authService.getUserId(),
      builder: (context, snapshot) {
        if(snapshot.hasData) 
        return StreamBuilder(
          stream: fireFirestore.instance.collection('properties').where('uid', isEqualTo: snapshot.data) .snapshots(),
          builder: (context, snapshot) {
            ...
          },
        );

        return Text('future had no data');
      },
    ),
  );
}