Flutter展示SQL存储的FAQ数据:解决JSON格式答案展示问题
解决方案
1. 修正FAQ模型的JSON解析逻辑
当前answer字段存在两种格式:JSON字符串(步骤类答案)和普通文本。需要在解析时自动识别并解码JSON内容,避免直接显示原始JSON字符串。
修改FAQ类的fromJson方法,添加辅助函数处理answer字段:
import 'dart:convert'; List<FAQ> faqFromJson(String str) => List<FAQ>.from(json.decode(str).map((x) => FAQ.fromJson(x))); String faqToJson(List<FAQ> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class FAQ { final int? id; final String? title; final String? question; final dynamic answer; final String? image; final DateTime? createdDate; final DateTime? updateDate; FAQ({ this.id, this.title, this.question, this.answer, this.image, this.createdDate, this.updateDate, }); // 辅助函数:区分JSON格式和普通文本的answer static dynamic _parseAnswer(dynamic rawAnswer) { if (rawAnswer is String) { try { // 尝试解码JSON,成功则返回解析后的对象 return json.decode(rawAnswer); } catch (_) { // 解码失败,返回原字符串 return rawAnswer; } } return rawAnswer; } factory FAQ.fromJson(Map<String, dynamic> json) => FAQ( id: json["id"], title: json["title"], question: json["question"], answer: _parseAnswer(json["answer"]), // 替换原直接赋值逻辑 image: json["image"], createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), updateDate: json["updateDate"], ); Map<String, dynamic> toJson() => { "id": id, "title": title, "question": question, "answer": answer, "image": image, "createdDate": createdDate?.toIso8601String(), "updateDate": updateDate, }; }
2. 优化UI展示逻辑
根据answer的类型(解析后的JSON对象或普通字符串),分别渲染步骤化列表或普通文本:
修改faqlist方法,替换subtitle的实现:
Widget faqlist(BuildContext context, Size size, List<FAQ> data) { return SizedBox( child: ListView.builder( scrollDirection: Axis.vertical, itemCount: data.length, shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return ListTile( title: Text(data[index].question ?? ''), subtitle: _buildAnswerContent(data[index].answer), ); }, ), ); } // 根据answer类型构建对应展示组件 Widget _buildAnswerContent(dynamic answer) { // 处理步骤类答案(解析后的JSON数组) if (answer is List) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: answer.expand((stepItem) { // 遍历步骤Map,生成每条步骤的文本 return (stepItem as Map<String, dynamic>).entries.map((entry) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text( '${entry.key}: ${entry.value}', style: const TextStyle(height: 1.4), ), ); }); }).toList(), ); } // 处理普通文本答案 else { return Text(answer?.toString() ?? ''); } }
效果说明
- 对于
Question 1这类JSON格式的步骤答案,会自动解析并逐条展示每个步骤(如Step 1: Here、Step 2: Heree) - 对于
Question 2这类普通文本答案,会直接显示原始内容
内容的提问来源于stack exchange,提问作者user21992191
相关产品推荐
相关产品推荐

