【问题标题】:How to rewrite this in dart to avoid the cast error如何在 dart 中重写它以避免转换错误
【发布时间】:2021-07-12 02:48:45
【问题描述】:

我有这段代码,我想返回一个文档快照流。

/* Get Firestore products docs
 */
  Stream<List<DocumentSnapshot>> fetchFirstProductListStream() {
    
    ....
   return  getFirestoreUserStream(loggedInUser.uid).map((UserModel rad) => 
    (geo
          .collection(collectionRef: collectionReference)
          .within(center: center, radius: rad.radius, field: field)) as List<DocumentSnapshot>
    );
}

当我尝试将返回值转换为 List 时,我确实收到了以下错误。

> [VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: type
> '_AsBroadcastStream<List<DocumentSnapshot>>' is not a subtype of type > > 'List<DocumentSnapshot>'

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你有两个选择:

    选项1: 因为您最终将数据转换为普通列表。直接返回。您现在不需要 StreamStreamBuilder 来解析它。您可以直接使用ListView.builder() 来渲染数据:

    List<DocumentSnapshot> fetchFirstProductListStream() {
        
    ....
       return  getFirestoreUserStream(loggedInUser.uid).map((UserModel rad) => 
        (geo
              .collection(collectionRef: collectionReference)
              .within(center: center, radius: rad.radius, field: field)) as List<DocumentSnapshot>
        );
    }
    

    选项 2: 从 API 返回一个真正的 Stream 并使用 StreamBuilder 异步读取它:

    查看此SO Post

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 2019-01-10
      • 2020-03-15
      • 2017-03-10
      • 2020-12-03
      • 2014-05-27
      • 2020-09-06
      • 1970-01-01
      • 2010-09-14
      相关资源
      最近更新 更多