Home > OS >  How to update a variable using the get package with flutter?
How to update a variable using the get package with flutter?

Time:02-25

I'm experimenting a bit with flutter and the get package and so far I like it. The only problem I have at the moment is that I cannot understand how to update an obs variable with a new value instead of just incrementing it as described in the tutorial:

class Controller extends GetxController{
  var count = 0.obs;
  increment() => count  ;
}

In my case, I have a variable called id in my controller which I would like to update to a brand new value when an element on my left menu is clicked. Roughly the code is the following:

my controller

import 'package:get/get.dart';

class MainController extends GetxController {
  var id = 0.obs;
  setId(var newId) {
    print("Inside setId");
    id = newId;
  }
}

the function is called when an element of the menu is pressed

onTap: () {
    c.setId(this.widget.identifier);
},

I have a reference to the MainController

final MainController c = Get.find();

Currently, when I pressed on my menu I have the following error:

Inside setId

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following TypeErrorImpl was thrown while handling a gesture:
Expected a value of type 'RxInt', but got one of type 'int'

I tried to create an Rx variable in multiple ways but no luck so far.

Can anyone show me how to fix this? Is there a better way to update a variable in the controller?

Thanks

CodePudding user response:

I created demo project with GetX. Refer this code. -> https://github.com/dhola-hardik/flutter_getx_example

CodePudding user response:

right after I posted this question I found the solution to my problem. I'll leave the like to the answer here but in short you need to update id.value instead of just the id

The more detailed answer

  • Related