Flutter集成Dialogflow机器人无法显示自定义Payload解决方法
问题根因
你参考的官方入门codelab教程内的示例代码,默认仅读取Dialogflow返回的fulfillmentText纯文本字段,未实现richContent自定义载荷字段的解析与渲染逻辑,因此配置的图片、卡片类富内容无法展示。另外你当前返回的JSON中图片rawUrl的id参数后多了一个多余空格,就算完成富内容解析也会导致图片加载失败。
修复步骤
- 先修正Dialogflow控制台内的配置:将图片
rawUrl里id=后的多余空格删除,修正为https://drive.google.com/uc?id=19-CnfYQB3Mp7jK4O99k_M8hMqptBaP3b,排除地址格式错误问题。 - 修改Flutter侧Dialogflow响应解析逻辑:在原有获取纯文本响应的代码基础上,新增
richContent字段的读取逻辑,参考代码如下:
// 保留原有纯文本读取逻辑 String responseText = response.queryResult.fulfillmentText ?? ""; List<dynamic> richContentList = []; // 读取富内容字段,注意不同SDK版本字段挂载层级可能有区别 if (response.queryResult?.richContent != null) { richContentList = response.queryResult.richContent; } else if (response.data?["queryResult"]?["richContent"] != null) { richContentList = response.data["queryResult"]["richContent"]; }
- 改造聊天消息渲染组件:新增富内容类型判断分支,匹配到
type为image的内容时,使用网络图片组件加载渲染,参考代码如下:
Widget _buildChatBubble(dynamic content) { // 图片类型富内容渲染 if (content["type"] == "image") { return Container( margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 8), child: Image.network( content["rawUrl"], width: 200, fit: BoxFit.cover, errorBuilder: (context, err, stack) => const Text("图片加载失败"), ), ); } // 保留原有纯文本消息渲染逻辑 return Container( margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 8), padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.grey[200], borderRadius: BorderRadius.circular(8), ), child: Text(content["text"] ?? ""), ); }
- 调整消息列表的数据组装逻辑:注意
richContent是二维数组结构,遍历的时候要先拆解外层数组,再遍历内层的每一项富内容,把解析到的富内容项和纯文本内容一起加入消息列表,再通知页面刷新即可。
后续如果需要支持按钮、信息卡片等其他自定义Payload,只需要在渲染组件里新增对应
type的判断分支,按相同逻辑处理即可。
内容的提问来源于stack exchange,提问作者Daniel Gosjen
相关产品推荐
相关产品推荐

