【问题标题】:How to query data from Firebase with an async call to uid如何通过异步调用 uid 从 Firebase 查询数据
【发布时间】:2020-01-16 09:53:49
【问题描述】:

我正在尝试获取属于已登录用户的数据,但是,由于某种原因,“getuserui”是异步的。即使用户已登录在应用程序内执行操作,该函数仍会返回 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&lt;null&gt; can't be assigned to the parameter type Stream

【问题讨论】:

    标签: firebase flutter future


    【解决方案1】:

    首先,您将异步函数作为流传递,因此您的错误。其次,您需要将 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');
          },
        ),
      );
    }
    

    【讨论】:

    • 天哪,我为此损失了 2 天时间。(我完全不熟悉颤振)我可能每次需要这个,例如用户照片等,对吧?你是一个活生生的救星,当然应该给你一块饼干!谢谢
    • @raiton 是的。每当您的小部件依赖于未来的结果时,请考虑 FutureBuilder。很高兴,我们都去过那里。
    猜你喜欢
    • 1970-01-01
    • 2018-05-01
    • 2022-07-05
    • 1970-01-01
    • 2021-08-16
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多