Hive conversations / messages architecture in Flutter

Viewed 197

I would like to use hive in my Flutter app to save locally conversations and messages of the conversations for the current user.

That being said, i especially would like to retrieve all of the messages for a specific conversation.

Should I create boxes as the conversation_id as name to store messages ?
If i am correct, this would create 1 file per box, so is it correct to have possibly hundreds of files for this ? Does it sound reasonable ?

What would be the best way in this situation ?

So far i only have two boxes Messages and Conversations but as we can't "query", if i want to load messages for a specific conversation, i need to load ALL messages of ALL conversations and then filter in dart, which can eventually lead to Ouf Of Memory crash issue.

I have tested it with 100k messages to get the OOM, but i am seeing this on the long-run of course as a user will not have 100K messages before a very long time, but anyway it would improve performances.

Thanks in advance

1 Answers

I think u should add 2 more,

@HiveField(5)
late int conversationId;

@HiveField(6)
late bool isMe;

// 5 and 6 just distinct hive numbers

you should store conversationId and isMe variables on each messages with your existing varibales.

and when you try to display messages through this method,

Expanded(
            child: Container(
          color: Colors.grey.shade100,
          child: ValueListenableBuilder<Box<ChatStore>>(
            valueListenable: Boxes.getTransactions().listenable(),
            builder: (context, box, _) {
              final transactions = box.values
                  .toList()
                  .where((element) => element.conversationId == 1111)
                  .cast<ChatStore>();

              return buildContent(transactions.toList());
            },
          ),
        )),

check conversation id with desired id example 1111 and isMe to change your right left alignment for two user.

//color: transaction.isMe == true ? Colors.white : Colors.green,

Widget buildContent(List<ChatStore> transactions) {
if (transactions.isEmpty) {
  return const Center(
    child: Text(
      'No messages yet!',
      style: TextStyle(fontSize: 24),
    ),
  );
} else {
 your logic to display messages
}

hope it helps

Related