You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:27:42