Home > Back-end >  Firestore: Adding a list of custom objects crashes my app
Firestore: Adding a list of custom objects crashes my app

Time:07-24

Im currently writing an app in flutter with a firestore backend. I have a document that stores an array of message objects. Id like to be able to write a list of messages to update this document in certain cases. So far, Im doing the following:

Goal: Firestore screenshot Firestore method:

  Future<void> updateStingrayMessageLikeCount(
      Message? message, String? stingrayid, List<Message?> messages) async {
    return FirebaseFirestore.instance
        .collection('stingrays')
        .doc(stingrayid)
        .collection('messages')
        .doc(message!.chatId)
        .update(
          {
            'messages': [Message.messageListToJson(messages)]
          },
        )
        .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"));
  }

Mapping functions:

  static Map<String, dynamic> toJson(Message? message) => {
        'id': message?.id,
        'senderId': message?.senderId,
        'receiverId': message?.receiverId,
        'message': message?.message,
        'dateTime': message?.dateTime,
        'timeString': message?.timeString,
        'likes': message?.likes,
        'chatId': message?.chatId,
        'commentCount': message?.commentCount,
        'userIdsWhoLiked': message?.userIdsWhoLiked,
      };

  static List messageListToJson(List<Message?> messages) {
    List messageList = [];
    for (Message? message in messages) {
      messageList.add(Message.toJson(message));
    }
    return messageList;
  }

The error occurs after messageList is returned. When firestore tries to set the document, my entire app crashes and i cant get an error code. Any idea what is going on?

CodePudding user response:

Oh my god im an idiot.

In

'messages': [Message.messageListToJson(messages)]

I have brackets surrounding my list. This has been a worthwhile 3 hours of debugging :].

CodePudding user response:

You will need to add Await in your Future Async function when you call your firebase data :

Future<void> updateStingrayMessageLikeCount(
      Message? message, String? stingrayid, List<Message?> messages) async {
    return await FirebaseFirestore.instance
        .collection('stingrays')
        .doc(stingrayid)
        .collection('messages')
        .doc(message!.chatId)
        .update(
          {
            'messages': [Message.messageListToJson(messages)]
          },
        )
        .then((value) => print("User Updated"))
        .catchError((error) => print("Failed to update user: $error"));
  }
  • Related