publishResult method

void publishResult(
  1. String pollId
)

Implementation

void publishResult(String pollId) async {
  try {
    // Creating the necessary maps to represent your JSON objects
    Map<String, dynamic> dataObject = {};
    Map<String, dynamic> resultObject = {};
    Map<String, dynamic> optionsObject = {};
    var questionAndAnswers = getQuestionsAndAnswersByPollId(pollId);
    var question = questionAndAnswers.keys.first;
    var answers = questionAndAnswers[question];

    // Iterate over the expandableDetailList to populate options and result
    answers?.asMap().forEach((index, answer) {
      String number = (index + 1).toString();
      optionsObject['opt$number'] = answer.title ?? 'Unknown Answer';  // Null safety
      resultObject['opt$number'] = answer.numberOfPoll;  // Initialize the result to 0
      print('Answer: ${answer.title}, Percentage: ${answer.percentage ?? 0}%');
    });

    // Populate dataObject with the necessary fields
    dataObject["type"] = "MCQ1";
    dataObject["question"] = question.questionTitle;
    dataObject["status"] = question.status;
    dataObject["total_result"] = question.totalPollCount;
    dataObject["id"] = question.pollConst;
    dataObject["timestamp"] = question.timeStamp;

    // Check for optional fields like duration and confNumber
    if (question.duration != 0) {
      dataObject["duration"] = question.duration;
    }

    if (question.confNumber != null && question.confNumber.isNotEmpty) {
      dataObject["conf_num"] = question.confNumber;
    }

    // Add the options and results to the data object
    dataObject["options"] = optionsObject;
    dataObject["result"] = resultObject;

    Map<String, dynamic> publishPoll = {
      'type': 'poll-data',
      'data': dataObject,
    };
    // Await the user list fetch
    List<String> moderatorClientIds = [];
    try {
      final userList = await EnxRtc.getUserList();
      for (var user in userList) {
        if ((user['role'] as String).toLowerCase() == 'moderator') {
          if (userModelSelf?.clientId != user['clientId']) {
            moderatorClientIds.add(user['clientId']);
          }
        }
      }
    } catch (error) {
      print('Error fetching user list: $error');
    }
    // Loop through the user list in the room



    // If there are moderator client IDs, send data to them
    if (isAll.value) {

      if(moderatorClientIds.isNotEmpty){
        EnxRtc.sendUserData(publishPoll, false, moderatorClientIds);
      }else{

        showToastMessage("No Moderator Available!");
      }

    }else{
      print("publishPoll ${jsonEncode(publishPoll)}");
      EnxRtc.sendUserData(publishPoll, true, []);
    }


    // Call your polling event with the dataObject
  } catch (e) {
    print("Error: $e");
  }
}