How can I gather and show results of a survey made with survey_kit package in Flutter?

Viewed 238

I am struggling in retrieving the results obtained from a survey built with survey_kit package. A SurveyResult object is supposed to contain a list of StepResults and the FinishReason. The StepResult contains a list of QuestionResults. I cannot access the StepResult in anyway.

Example proposed in the documentation:

SurveyKit
(
    onResult: (SurveyResult result) {
    //Read finish reason from result (result.finishReason)
    //and evaluate the results }
)

I already tried to tap something like result.stepResult but no variable was suggested.

1 Answers

I'm not sure if its the best approach but after looking into SurveyKit I've found that the SurveyResult class holds a list of StepResult and each of them holds a list of QuestionResult which in turn holds a value field called valueIdentifier.

so you can Iterate over them and extract the values. but first, you need to ensure that all of your answers have value. for example:

answerFormat: const SingleChoiceAnswerFormat(
     textChoices: [
          TextChoice(text: 'option 1', value: '10'),
          TextChoice(text: 'option 2', value: '-2'),
     ]
),

Then after you did that iterate over them like that:

onResult: (SurveyResult result) {
     int score = 0;
     for (var stepResult in result.results) {
          for (var questionResultin stepResult.results) {
               score += int.tryParse(questionResult.valueIdentifier ?? "0") ?? 0;
          }
     }
     print("final Score is $score");
     /* call a new widget to show the results*/
 },

As you can see I use two null checks when adding a question value to the score.
The first one is because the value is of type "String?" (and not "String") and the second one is because the String value might be non-numeric.

Of course, after you have calculated the results you can show the result on a new screen with Navigator.

Related