toggleReaction method

void toggleReaction(
  1. String messageId,
  2. String emoji, {
  3. String? userName,
})

Toggles a reaction with the given emoji for a messageId.

If the user has already reacted with the emoji, it's removed. Otherwise, it's added.

Implementation

void toggleReaction(String messageId, String emoji, {String? userName}) {
  final reactions = _messageReactions[messageId] ?? [];
  final userReactionIndex =
      reactions.indexWhere((r) => r.userId == currentUserId);

  if (userReactionIndex != -1) {
    final existingReaction = reactions[userReactionIndex];
    // If the user is selecting the same reaction, remove it.
    if (existingReaction.emoji == emoji) {
      removeReaction(messageId, emoji);
    } else {
      // If the user is selecting a different reaction, replace the old one.
      reactions.removeAt(userReactionIndex);
      addReaction(messageId, emoji, userName: userName);
    }
  } else {
    // If the user has no reaction, add the new one.
    addReaction(messageId, emoji, userName: userName);
  }
}