Home > Enterprise >  Async function printing empty value
Async function printing empty value

Time:10-24

When I call my function "randomChat" it somehow returns an empty value, which should not happen with my code.

randomChat Function:

    Future<String> randomChat(String userId) async {
  String roomId = await connectRoom(userId);
  return roomId;
}

connectRoom Function:

   Future<String> connectRoom(String userId) async {
  List<String> connectedUsers = await getChattingWith(userId);
  late String roomId;

  // Find all the rooms where userId2 is empty
  FirebaseFirestore.instance
      .collection('rooms')
      .where('userId2', isEqualTo: "")
      .where("userId1", isNotEqualTo: userId)
      .get()
      .then((snapshot) async {
    // If no empty room is found, create room
    if (snapshot.docs.isEmpty) {
      print("call empty");
      String roomId = await createRoom(userId);
      return roomId;
    }

//        // If an empty room which is not connected to userId (part of connectedUsers) is found, connect to it
    for (int i = 0; i < snapshot.docs.length; i  ) {
      var data = snapshot.docs[i].data();
      Room room = Room.fromJson(data);
// check if the empty room found is not connected to userId
      bool found = connectedUsers.contains(room.userId1);

      if (!found) {
        FirebaseFirestore.instance
            .collection('rooms')
            .doc(room.id)
            .update({"userId2": userId});
        print("call not found = $roomId");
        return roomId = room.id;
      } else {
        
        roomId = await createRoom(userId);
        print("call found = $roomId");
        return roomId;
      }
    }
  });
  print("call nothing = $roomId");
  return roomId;
}

And here I am calling the function and printing the value (which is empty, but should not be empty. It should return my roomId):

   onPressed: () async {
                String roomId = await randomChat(uid);
                print(roomId);
     
              },

Create Room function (where I also correctly get the roomId printed):

    Future<String> createRoom(String userId) async {
  DocumentReference docRef =
      await FirebaseFirestore.instance.collection("rooms").add({
    "userId1": userId,
    "userId2": "",
    "created_at": DateTime.now().toString(),
  });
  await docRef.update({"roomId": docRef.id});
  print("create room: ${docRef.id}");
  return docRef.id;
}

CodePudding user response:

In your connectRoom, you need to await for FirebaseFirestore result:

await FirebaseFirestore.instance
      .collection('rooms')
      .where('userId2', isEqualTo: "")
      .where("userId1", isNotEqualTo: userId)
      .get()
      .then((snapshot) async {
  ...
}

also you define new String roomId in every if statement inside then function, just pass that value to your main roomId which is define as late String roomId.

  • Related