【问题标题】:Flutter GetX state management can't update the variables stateFlutter GetX 状态管理无法更新变量状态
【发布时间】:2021-12-10 20:51:26
【问题描述】:

我无法使用 .obsRxTypeRx() 更改任何变量的状态;

当我尝试更改它时,它会给出无法将值类型 int 分配给变量类型 RxInt 的错误。 代码如下:

class StateController extends GetxController {
   late String sunrise;
   late String sunset;
   late int temperatureDegree;
   late int maxDegree;
   late int minDegree;
   late double windSpeed;
   late int humidity;


 void updateUI(dynamic weatherDataInput) {
    sunrise = weatherDataInput["current"]["sunrise"];
    sunset = weatherDataInput["current"]["sunset"];
    temperatureDegree = weatherDataInput["current"]["temp"];
    maxDegree = weatherDataInput["daily"][0]["temp"]["max"];
    minDegree = weatherDataInput["daily"][0]["temp"]["min"];
    windSpeed = weatherDataInput["current"]["wind_speed"];
    humidity = weatherDataInput["current"]["humidity"];
   }
 }

【问题讨论】:

  • 你试过把update();在下面的 updateUI 上?如果它的调用更新你需要使用 getbuilder 如果不尝试在下面理解我的

标签: flutter dart state-management flutter-getx


【解决方案1】:

试试这个方法

    class NameController extends GetxController{
    
     final sunrise = ''.obs;
    
     void updateSomeText(){
      sunrise('Text updated'); //or  sunrise(weatherDataInput["current"] 
  //["sunrise"].toString());
     }
    }

然后更新它尝试用 Obx 包装它,例如:

final controller = Get.put(NameController());

  Obx(
()=> Text(controller.sunrise.value)
),

【讨论】:

    【解决方案2】:

    您可以像这样在 updateUI() 末尾使用update() 方法:

       void updateUI(dynamic weatherDataInput) {
        sunrise = weatherDataInput["current"]["sunrise"];
        sunset = weatherDataInput["current"]["sunset"];
        temperatureDegree = weatherDataInput["current"]["temp"];
        maxDegree = weatherDataInput["daily"][0]["temp"]["max"];
        minDegree = weatherDataInput["daily"][0]["temp"]["min"];
        windSpeed = weatherDataInput["current"]["wind_speed"];
        humidity = weatherDataInput["current"]["humidity"];
        update(); 
    }
    

    , 然后在您的 UI 中使用 GetBuilder,或者,您应该将变量声明为 Rx,例如:

    RxString sunrise = "".obs;
    RxString sunset = "".obs;
    

    并在您的 UI 中使用观察者小部件:

    Obx(
    ()=> Text(controller.sunset.value)
    )
    

    这将在可观察对象(日出和日落)发生变化时自动更新您的 UI。 .

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2021-11-06
      • 2022-01-21
      相关资源
      最近更新 更多