customerDetailGet['customer_transaction_detail']
接收数组列表 如何将数组列表分配给作为模型的 CustomerTransactionDetail 列表
完整代码
实际使用Provider。我有 Customer Transaction Detail 的模型,所以我想分配新的接收列表数组也添加到之前的 CustomerTransactionDetail 列表中 但错误
var url = Uri.https(BaseUrl.apiBaseUrl,
BaseUrl.apiBaseUrlSecond + 'add_customer.php', {});
Map object = {
"c_name": nameController.text,
"c_mobile": mobileController.text,
"c_address": addressController.text,
"login_id": Constants.loginId,
};
var source = await http.post(url, body: jsonEncode(object));
if (source.statusCode == 200) {
if (jsonDecode(source.body)["status"] == 200) {
var message = jsonDecode(source.body)["result"]["message"];
var customerDetailGet =
jsonDecode(source.body)["result"]["customer_detail"];
var customerDetail = CustomerDetail(
accountType: customerDetailGet['account_type'],
address: customerDetailGet['address'],
conversationNo: customerDetailGet['conversation_no'],
currentBalance: customerDetailGet['current_balance'],
customerTransactionDetail: customerDetailGet['customer_transaction_detail'], // error line
id: customerDetailGet['id'],
mobile: customerDetailGet['mobile'],
name: customerDetailGet['name'],
status: customerDetailGet['status'],
);
int debitBalance = jsonDecode(source.body)["result"]
["credit_debit_balance"]["debit_balance"];
int creditBalance = jsonDecode(source.body)["result"]
["credit_debit_balance"]["credit_balance"];
Provider.of<CustomerAndTransactionClassProvider>(context,
listen: false)
.addCustomer(customerDetail, debitBalance, creditBalance);
setState(() {
responseResult = message;
isLoadding = false;
});
Navigator.pop(context);
} else if (jsonDecode(source.body)["status"] == 202) {
setState(() {
responseResult = jsonDecode(source.body)["result"]["message"];
isLoadding = false;
});
} else {
setState(() {
responseResult = "sorry try again";
isLoadding = false;
});
}}
答案 0 :(得分:1)
您必须指定变量 customerDetailGet
的类型。
如果不这样做,Dart 会假定它是一个 dynamic
并且可能无法按照您想要的方式处理它(这会导致您遇到异常)。
指定类型最简单的方法是写:
List<CustomerTransactionDetail> customerDetailGet = List<CustomerTransactionDetail>.from(
jsonDecode(source.body)["result"]["customer_detail"]
);
但是,如果 CustomerTransactionDetail
不是基本类型之一的子类型,这可能会失败。
因此,您可能需要创建一个新列表并实例化所有值:
List<CustomerTransactionDetail> customerDetailGet = List<CustomerTransactionDetail>.from(
jsonDecode(source.body)["result"]["customer_detail"].map(
(customerDetail) => CustomerTransactionDetail.fromJson(customerDetail)
)
);
在这种情况下,您必须实现 factory constructor CustomerTransactionDetail.fromJson
。