Flutter如何提取CashfreePGSDK返回Map键值对数据存入自定义变量
实现方案
你可以选择以下两种方式实现字段存储,根据你的项目复杂度选择即可:
方案1:直接判断key赋值(适合快速开发)
先在当前作用域提前声明需要接收的变量,再遍历键值对匹配赋值即可,代码示例如下:
// 提前声明接收变量 String? txStatus; String? orderAmount; String? paymentMode; String? orderId; String? txTime; String? signature; String? txMsg; String? type; String? referenceId; CashfreePGSDK.doPayment(inputParams) .then((value) { if (value == null) return; value.forEach((key, val) { switch(key) { case "txStatus": txStatus = val; break; case "orderAmount": orderAmount = val; break; case "paymentMode": paymentMode = val; break; case "orderId": orderId = val; break; case "txTime": txTime = val; break; case "signature": signature = val; break; case "txMsg": txMsg = val; break; case "type": type = val; break; case "referenceId": referenceId = val; break; } }); // 赋值完成后即可使用变量处理后续逻辑 });
方案2:模型类封装(适合正式项目,可维护性更高)
先定义响应结果的实体类,将返回的Map直接转换为实体对象,后续通过点语法即可读取所有字段:
步骤1:定义实体类
class CashFreeResponse { final String? txStatus; final String? orderAmount; final String? paymentMode; final String? orderId; final String? txTime; final String? signature; final String? txMsg; final String? type; final String? referenceId; CashFreeResponse({ this.txStatus, this.orderAmount, this.paymentMode, this.orderId, this.txTime, this.signature, this.txMsg, this.type, this.referenceId, }); factory CashFreeResponse.fromMap(Map map) { return CashFreeResponse( txStatus: map["txStatus"], orderAmount: map["orderAmount"], paymentMode: map["paymentMode"], orderId: map["orderId"], txTime: map["txTime"], signature: map["signature"], txMsg: map["txMsg"], type: map["type"], referenceId: map["referenceId"], ); } }
步骤2:回调内转换使用
CashfreePGSDK.doPayment(inputParams) .then((value) { if (value == null) return; CashFreeResponse response = CashFreeResponse.fromMap(value); // 直接读取字段使用示例 String status = response.txStatus ?? ""; String amount = response.orderAmount ?? ""; });
注意事项
- 若需要对
orderAmount做数值计算,可通过double.parse(response.orderAmount ?? "0")转换为双精度类型使用 - 建议对所有读取的字段做空兼容处理,避免返回字段缺失时出现空异常
内容的提问来源于stack exchange,提问作者Roxx
相关产品推荐
相关产品推荐

