Flutter中如何合并API返回的Client与Phones数据生成Supplier对象
问题
调用API创建数据时,API返回包含client对象和phones数组的响应,需要将client的属性整合到supplier对象中,并添加phones数组,生成指定结构的supplier数据。
API响应示例
{ "client": { "name": "Glorymawn", "address": "bole", "tin_no": 98909876, "updated_at": "2022-10-11T16:23:00.000000Z", "created_at": "2022-10-11T16:23:00.000000Z", "id": 24 }, "phones": [ { "id": 59, "client_id": 23, "phone_number": 90865132314, "email": "ism3e@mail.com", "model": "Supplier", "category": "Manager", "created_at": "2022-10-11T16:23:00.160624Z", "updated_at": "2022-10-11T16:23:00.160636Z" } ], "message": "Client created successfully" }
目标supplier结构
{ "supplier": { "id": 24, "name": "Glorymawn", "address": "bole", "tin_no": "98909876", "created_at": "2022-10-11T16:23:00.000000Z", "updated_at": "2022-10-11T16:23:00.000000Z", "phones": [ { "id": 59, "client_id": 23, "phone_number": 90865132314, "email": "ism3e@mail.com", "model": "Supplier", "category": "Manager", "created_at": "2022-10-11T16:23:00.160624Z", "updated_at": "2022-10-11T16:23:00.160636Z" } ] } }
当前createSupplier代码
Future createSupplier( String name, String address, String tin_no, List<Phones> phones) async { Uri url = Uri.parse("${BASE_URL}supplier"); SupplierController supplierController = Get.put(SupplierController()); final response = await http .post(url, headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer $TOKEN', }, body: jsonEncode<String, dynamic>({ 'name': name, 'address': address, 'tin_no': int.parse(tin_no), 'phones': phones.toList() })) .then((value) { if (value.statusCode == 200) { supplierController.setsupplierPress(true); print(json.decode(value.body)['client']); supplierController.createSupplier( Suppliers.fromJson(json.decode(value.body)['client'])); Get.back(); supplierController.setsupplierPress(false); print('<<<<<<<<<<' + value.body); print(json.decode(value.body)['client']); print("success"); } else if (value.statusCode == 500) { Get.snackbar("Data Exists", "The data you provided already exists."); } else { Get.snackbar("Failed", "Failed to create client, try again later"); } }); }
解决方案
修改API响应处理逻辑,将client和phones合并为目标结构的supplier,具体实现如下:
Future createSupplier( String name, String address, String tin_no, List<Phones> phones) async { Uri url = Uri.parse("${BASE_URL}supplier"); SupplierController supplierController = Get.put(SupplierController()); final response = await http.post( url, headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer $TOKEN', }, body: jsonEncode({ 'name': name, 'address': address, 'tin_no': int.parse(tin_no), 'phones': phones.map((phone) => phone.toJson()).toList() }), ); if (response.statusCode == 200) { supplierController.setsupplierPress(true); final decodedBody = json.decode(response.body); // 整合client数据并处理tin_no转字符串,添加phones数组 final supplierData = { ...decodedBody['client'], 'tin_no': decodedBody['client']['tin_no'].toString(), 'phones': decodedBody['phones'] }; // 传递完整的supplier对象给控制器 supplierController.createSupplier(Suppliers.fromJson(supplierData)); Get.back(); supplierController.setsupplierPress(false); print('<<<<<<<<<<' + response.body); print("success"); } else if (response.statusCode == 500) { Get.snackbar("Data Exists", "The data you provided already exists."); } else { Get.snackbar("Failed", "Failed to create client, try again later"); } }
配套修改说明
更新Suppliers模型类
确保模型包含phones字段,否则无法正确解析:class Suppliers { final int id; final String name; final String address; final String tinNo; final String createdAt; final String updatedAt; final List<Phones> phones; Suppliers({ required this.id, required this.name, required this.address, required this.tinNo, required this.createdAt, required this.updatedAt, required this.phones, }); factory Suppliers.fromJson(Map<String, dynamic> json) { return Suppliers( id: json['id'], name: json['name'], address: json['address'], tinNo: json['tin_no'], createdAt: json['created_at'], updatedAt: json['updated_at'], phones: (json['phones'] as List).map((p) => Phones.fromJson(p)).toList(), ); } }补充Phones类的toJson方法
确保请求时能正确序列化phones数组:class Phones { // 原有字段定义... Map<String, dynamic> toJson() { return { 'client_id': clientId, 'phone_number': phoneNumber, 'email': email, 'model': model, 'category': category, }; } }
内容的提问来源于stack exchange,提问作者mobix
相关产品推荐
相关产品推荐

