Flutter GetX状态管理使用.obs、RxType等无法更新变量状态且赋值报错
问题根因
- 当前代码中定义的均为普通Dart基础类型变量,未声明为GetX要求的响应式Rx类型,无法使用
.obs相关响应式特性 - 若直接将普通类型值赋值给Rx类型变量(未通过
.value属性操作),就会抛出「无法将int类型值赋值给RxInt类型变量」的类型不匹配错误
修复步骤
- 先将所有变量声明为响应式类型,GetX提供三种等价声明方式,任选其一即可:
- 后缀法:
final count = 0.obs;(最常用) - 构造法:
final count = RxInt(0); - 显式声明:
RxInt count = 0.obs;
- 后缀法:
- 响应式变量的取值、赋值都必须通过
.value属性操作
完整可运行代码
class StateController extends GetxController { // 统一用后缀法声明响应式变量,指定初始值避免空安全问题 final sunrise = ''.obs; final sunset = ''.obs; final temperatureDegree = 0.obs; final maxDegree = 0.obs; final minDegree = 0.obs; final windSpeed = 0.0.obs; final humidity = 0.obs; void updateUI(dynamic weatherDataInput) { // 所有赋值操作修改.value属性 sunrise.value = weatherDataInput["current"]["sunrise"]; sunset.value = weatherDataInput["current"]["sunset"]; temperatureDegree.value = weatherDataInput["current"]["temp"]; maxDegree.value = weatherDataInput["daily"][0]["temp"]["max"]; minDegree.value = weatherDataInput["daily"][0]["temp"]["min"]; windSpeed.value = weatherDataInput["current"]["wind_speed"]; humidity.value = weatherDataInput["current"]["humidity"]; } }
页面使用说明
需要自动刷新的UI组件用Obx包裹,直接读取变量的.value即可:
Obx(() => Text("当前温度:${controller.temperatureDegree.value}°"))
内容的提问来源于stack exchange,提问作者Hama Sabah
相关产品推荐
相关产品推荐

