Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Convert firestore snapshot to list in streambuilder

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>'
like image 377
Eduardo Andres Avatar asked Oct 16 '25 03:10

Eduardo Andres


1 Answers

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 = [];
like image 187
Peter Haddad Avatar answered Oct 17 '25 18:10

Peter Haddad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!