Home > Blockchain >  Flutter GetX state management can't update the variables state
Flutter GetX state management can't update the variables state

Time:10-25

I Can't Change the state of any variable with .obs, RxType and Rx();

And when i try to change it it will give errors that ican't assign a value type int to variable type RxInt. Here is the code:

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"];
   }
 }

CodePudding user response:

try this way,

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

then to update it try wrap it with Obx e.g.:

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

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

CodePudding user response:

You can use the update() method in the end of the updateUI() like this:

   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(); 
}

, and then use GetBuilder in your UI, alternatively, you should declare your variables as Rx, for example:

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

and use observer widget in your UI:

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

This will update your UI automatically when observables (sunrise and sunset) change. .

  • Related