How to work with GetX Observable Variables?

Issue

I have a simple timer app whose UI includes this code snippet:

body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              child: Obx(
                () => CircularProgressIndicator(
                  value: <== This is what I'm asking about,
                ),
              ),
            ),

I want the CircularProgressIndicator to increment like a clock, changing its value 1/60 every second or minute. My GetxController class begins:

class Controller extends GetxController {
  Timer? timer;
  Duration timerInterval = Duration(seconds: 1);
  var time = 0;
  var strTime = '00:00'.obs;

It’s got methods with names like startTimer(), stopTimer(), and resetTimer().

If I make the Controller’s time field observable

var time=0.obs;

and then try to use that value in the CircularProgressIndicator

Obx(
      () => CircularProgressIndicator(
         value: timeController.time.value % 60,
       ),
    ),

I get an error that A value of type 'int' can't be assigned to a variable of type 'RxInt' centered on the marked line in the Controller:

 void resetTimer() {
if (timer != null) {
  timer!.cancel();
  timer = null;
  time = 0; <== This is the problematic line
}
strTime.value = '00:00';

I thought I needed to replace this code with time.value=0;but that just creates a new error message, type 'int' is not a subtype of type 'RxInt' of 'function result'.
What am I doing incorrectly?

Solution

In case someone needed this:

I tried the following and it’s working very fine with Getx:

Controller:

class TestController extends GetxController {
  Timer? timer;
  Duration timerInterval = const Duration(seconds: 1);
  RxInt time = 0.obs;
  var strTime = '00:00'.obs;
  @override
  void onInit() {
    timer = Timer.periodic(timerInterval, (_) {
      time.value = time.value + 1;
    });
    super.onInit();
  }

  void resetTimer() {
    if (timer != null) {
      timer!.cancel();
      timer = null;
      time.value = 0; // <== This is working fine
    }
    strTime.value = '00:00';
  }
}

View:

Obx(
  () => CircularProgressIndicator(
   value: testController.time.value / 60,
    ),
  ),

Answered By – Gwhyyy

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *