GetX无法设置Rx变量:CustomerInfo与_$CustomerInfoImpl类型不匹配
问题
我用GetX开发Flutter应用,想要将RevenueCat的CustomerInfo同步到应用中,添加了如下监听器:
Purchases.addCustomerInfoUpdateListener((CustomerInfo info) { print(info.runtimeType); customerInfo.value = info; });
我的GetX控制器中,customerInfo是Rx变量,定义为:
Rx<CustomerInfo?> customerInfo = null.obs;
但运行时发现监听器返回的info的runtimeType是_$CustomerInfoImpl而非CustomerInfo,尝试强制类型转换也无效,始终报错:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_$CustomerInfoImpl' is not a subtype of type 'Null' of 'v' #0 RxObjectMixin.call (package:get/get_rx/src/rx_types/rx_core/rx_impl.dart:62:14) #1 AccountController.onInit.<anonymous closure> (package:mitt_sjo_liv/controllers/account_controller.dart:311:19) #2 Purchases.addCustomerInfoUpdateListener (package:purchases_flutter/purchases_flutter.dart:191:33) #3 AccountController.onInit (package:mitt_sjo_liv/controllers/account_controller.dart:308:15)
解决办法
- 修正Rx变量初始化方式:把
null.obs的写法换成更明确的初始化形式,避免GetX的Rx类型处理异常:// 写法1:明确指定类型和初始值 final customerInfo = Rx<CustomerInfo?>(null); // 写法2:使用GetX的RxNullable便捷构造 final customerInfo = RxNullable<CustomerInfo>(); - 安全赋值处理:
_$CustomerInfoImpl本质是CustomerInfo的内部实现子类,理论上可直接赋值,若仍有问题,尝试显式转换确保类型匹配:Purchases.addCustomerInfoUpdateListener((info) { print(info.runtimeType); customerInfo.value = info as CustomerInfo; }); - 检查依赖版本:确认
purchases_flutter和get的版本兼容,尝试更新到最新稳定版,避免版本冲突导致的类型解析问题。 - 排查控制器生命周期:确保监听器在
onInit方法中正确注册,且控制器初始化逻辑中没有其他干扰customerInfo变量的代码。
内容的提问来源于stack exchange,提问作者Joona
相关产品推荐
相关产品推荐

