Flutter GetX填充JSON数据到RxList时报Response类型不匹配如何解决
Flutter GetX JSON数据填充RxList报错解决方案
报错原因说明
你遇到的Expected a value of type 'Response', but got one of type 'RxList'报错,是因为代码中将RxList类型的变量直接赋值给了用来接收接口请求结果的Response类型变量,同时你当前的模型类缺少JSON序列化能力,无法直接解析接口返回的JSON数据。
步骤1:修改模型类新增JSON反序列化能力
你的现有Machine类字段和接口返回的JSON字段不匹配,且没有解析JSON的方法,修改machine.dart代码如下:
class Machine { // 接口返回的_id为字符串类型,将id类型调整为String避免类型错误 final String id; // 接口返回的number字段对应模型的machineNumber final int machineNumber; final String manufacturer; final int cost; Machine({ required this.id, required this.machineNumber, required this.manufacturer, required this.cost, }); // 新增fromJson工厂方法,用于将JSONMap转换为Machine实体 factory Machine.fromJson(Map<String, dynamic> json) { return Machine( id: json['_id'], machineNumber: json['number'], manufacturer: json['manufacturer'], cost: json['cost'], ); } }
步骤2:修改控制器请求与赋值逻辑
你当前的控制器中是硬编码的模拟数据,需要调整为实际的接口请求+JSON解析逻辑,避免类型匹配错误,修改machine_controller.dart代码如下:
import 'package:get/get.dart'; import 'package:myapp/models/machine.dart'; class MachineController extends GetxController { var machines = RxList<Machine>(); @override void onInit() { super.onInit(); fetchMachines(); } void fetchMachines() async { try { // 发送接口请求,这里以GetX的GetConnect为例,替换为你的实际请求地址 Response response = await Get.get('你的接口请求URL'); if (response.statusCode == 200) { // 将接口返回的JSON数组转换为List<Machine> List<Machine> serverMachines = (response.body as List) .map((item) => Machine.fromJson(item)) .toList(); // 赋值到RxList,使用assignAll不需要操作.value,更符合GetX规范 machines.assignAll(serverMachines); } } catch (e) { print('请求或解析错误:$e'); } } }
额外使用说明
- 如果需要保留原有RxList中的数据,直接调用
machines.addAll(serverMachines)即可 - 如果需要完全替换原有数据,调用
machines.clear()后再执行assignAll即可 - 注意接口请求的Response类型变量不要和RxList变量混淆赋值,即可避免你遇到的类型报错
内容的提问来源于stack exchange,提问作者Felix Jost
相关产品推荐
相关产品推荐

