Flutter使用SurveyKit时如何将SurveyResult序列化为JSON
Flutter中SurveyKit结果序列化JSON并存为文件的实现
result.results是List<StepResult>类型的嵌套结构,内置类没有自带toJson方法,按以下步骤处理即可:
- 引入所需依赖
要将JSON写入本地文件,需要先在pubspec.yaml中添加path_provider依赖用于获取本地可写路径,之后在代码中导入以下包:import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:survey_kit/survey_kit.dart'; - 编写结果转换方法
遍历每一步的答题结果,根据题型拆解为字符串、数字、列表等JSON支持的基础类型,组装为可序列化的Map结构:List<Map<String, dynamic>> parseStepResults(List<StepResult> stepResults) { return stepResults.map((step) { final Map<String, dynamic> stepData = { 'step_id': step.id?.id, 'start_time': step.startDate?.toIso8601String(), 'end_time': step.endDate?.toIso8601String(), }; final res = step.result; // 按题型匹配解析答案 if (res is TextQuestionResult) { stepData['question_type'] = 'text'; stepData['answer'] = res.result; } else if (res is IntegerQuestionResult) { stepData['question_type'] = 'integer'; stepData['answer'] = res.result; } else if (res is ScaleQuestionResult) { stepData['question_type'] = 'scale'; stepData['answer'] = res.result; } else if (res is SingleChoiceQuestionResult) { stepData['question_type'] = 'single_choice'; stepData['answer'] = res.result?.map((option) => option.text).toList(); } else if (res is MultipleChoiceQuestionResult) { stepData['question_type'] = 'multiple_choice'; stepData['answer'] = res.result?.map((option) => option.text).toList(); } else if (res is BooleanQuestionResult) { stepData['question_type'] = 'boolean'; stepData['answer'] = res.result; } return stepData; }).toList(); } - 在回调中执行序列化和文件写入
替换原有onResult逻辑,转换结构后生成JSON字符串,再写入本地文件:onResult: (SurveyResult result) async { print(result.finishReason); // 转换为可序列化结构 final jsonData = parseStepResults(result.results); // 生成标准JSON字符串 final String jsonContent = jsonEncode(jsonData); // 以下为写入本地JSON文件的逻辑,不需要存文件可省略 final appDir = await getApplicationDocumentsDirectory(); final file = File('${appDir.path}/survey_${DateTime.now().millisecondsSinceEpoch}.json'); await file.writeAsString(jsonContent); },
注意:如果使用了自定义题型,只需要在
parseStepResults方法中增加对应题型的判断分支,将答案拆解为基础类型即可,JSON序列化不支持直接写入复杂类实例。
内容的提问来源于stack exchange,提问作者Balaborka
相关产品推荐
相关产品推荐

