Flutter: Convert firestore snapshot to list in streambuilder

2,768

Change:

item = snapshot.data;

into this:

item = snapshot.data.documents;

documents should return a List<DocumentSnapshot>, so also change the type of item:

List<DocumentSnapshot> item = [];
Share:
2,768
Eduardo Andres
Author by

Eduardo Andres

Updated on December 22, 2022

Comments

  • Eduardo Andres
    Eduardo Andres over 1 year

    I need to convert a snapshot from cloud firestore to a list, i know this is unnecessary to show the data but i need it to reorder the data based in other parameters, this is my code

     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;
          });
        });
      }
    

    and im getting this error

    ════════ 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>'