Flutter:将firestore快照转换为streambuilder中的列表

时间:2020-07-06 17:15:21

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

我需要将快照从Cloud Firestore转换为列表,我知道这不需要显示数据,但是我需要它根据其他参数对数据重新排序,这是我的代码

 Stream chatRooms;
  List item = [];

 Widget chatRoomsList() {
    return StreamBuilder(
      stream: chatRooms,
      builder: (context, snapshot) {
        if (snapshot.hasData &&
            !snapshot.hasError) {
          item = [];

          item = snapshot.data;

          return ListView.builder(
              itemCount: item.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return ChatRoomsTile(
                  otherUserUid:item[index]['arrayUsers']
                      .replaceAll("[", "")
                      .replaceAll(widget.user.uid, "")
                      .replaceAll("]", "")
                      .replaceAll(",", "")
                      .replaceAll(" ", ""),
                  chatRoomId:
                  item[index]["chatRoomId"],
                  user: widget.user,
                );
              });
        } else
            return Container();
      },
    );
  }

  @override
  void initState() {
    getUserInfogetChats();
    super.initState();
  }

  getUserInfogetChats() async {
    DatabaseMethods().getUserChats(widget.user.uid).then((snapshots) {
      setState(() {
        chatRooms = snapshots;
      });
    });
  }

我收到此错误

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following _TypeError was thrown building StreamBuilder<dynamic>(dirty, state: _StreamBuilderBaseState<dynamic, AsyncSnapshot<dynamic>>#48820):
type 'QuerySnapshot' is not a subtype of type 'List<dynamic>'

1 个答案:

答案 0 :(得分:1)

更改:

item = snapshot.data;

对此:

item = snapshot.data.documents;

documents应该返回一个List<DocumentSnapshot>,因此还要更改item的类型:

List<DocumentSnapshot> item = [];