Home > Blockchain >  "NoSuchMethodError: The method '[]' was called on null." Erro in my Stream
"NoSuchMethodError: The method '[]' was called on null." Erro in my Stream

Time:11-03

I am getting the Error "NoSuchMethodError: The method '[]' was called on null." from my stream. I tried to change my code several times and added print statements, which get printed correctly, but my Stream ends up returning an error, which is the one from the subject line. Any idea why? How can I Fix the error?

This is the result of the print data statement:

data:

{
   userId1: 59jTMEbvqFd8C8UhInksauAVNk63,
   userId2: 2ssfDEPhPhcIwInUWdlm0ReH5RZ2,
   latestMessageTime: Timestamp(seconds=1667140814, nanoseconds=334000000),
   lastMessageSenderId: 59jTMEbvqFd8C8UhInksauAVNk63, 
   created_at: 2022-10-26 19:44:13.793275, 
   latestMessage: TEST 3, 
   roomId: Qv30s8kATJbFJIWRdBEo
}

.

      Stream<RoomsListModel> roomsStream() async* {
    try {
      // get all active chats
      var rooms = await FirebaseFirestore.instance
          .collection("rooms")
          .where("users", arrayContains: userId)
          .orderBy("latestMessageTime", descending: true)
          .snapshots();
      print("rooms: $rooms");
// get Other user details
      await for (var room in rooms) {
        for (var doc in room.docs) {
          var data = doc.data() as Map<String, dynamic>;
          print("data: $data");
          var otherUser = await getOtherUser(
              data["users"][0] == userId ? data["users"][1] : data["users"][0]);
          print("otherUser: $otherUser");
          yield RoomsListModel(
              roomId: doc.id,
              userId: otherUser["user id"],
              avatar: otherUser["photoUrl"],
              name: otherUser["name"],
              lastMessage: data["latestMessage"],
              lastMessageTime: data["latestMessageTime"]);
        }
      }
    } catch (e) {
      print("Error: $e");
    }
  }

.

Future getOtherUser(String id) async {
  // get other user profile
  var user = await FirebaseFirestore.instance
      .collection("users")
      .doc(id)
      .get()
      .then((value) => value.data()) as Map<String, dynamic>;
  // return other user profile
  return user;
}

CodePudding user response:

change this:

var otherUser = await getOtherUser(
              data["users"][0] == userId ? data["users"][1] : data["users"][0]);

to this:

var otherUser = await getOtherUser(
              data["userId1"] == userId ? data["userId2"] : data["userId1"]);
  • Related