Flutter : How can I change variable with Getx?

Issue

I want to change the value of the counter to 0.
But every time I try, it’s not working and I can’t use increment() anymore.
I believe that solution would be simple but I can’t figure that out.

class Home extends StatelessWidget {
  final controller = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: IconButton(
        icon: Icon(Icons.offline_bolt),
        onPressed: () {
          controller.increment();
        },
      )),
      body: Center(
        child: Obx(() => Text('${controller.counter}')),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          controller.re();
        },
        child: Icon(Icons.access_alarms),
      ),
    );
  }
}

class Controller extends GetxController {
  var counter = RxInt(0);
  void increment() {
    counter++;
    update();
  }

  re() {
    counter = RxInt(0);
    update();
  }
}

Solution

If you are using the Reactive State Manager you don’t need to call the update() function.

For reseting the counter back to 0 just assign 0 to the .value property.

So change your Controller like this and it should work:

class Controller extends GetxController {
  var counter = RxInt(0);

  void increment() {
    counter++;
  }

  re() {
    counter.value = 0;
  }
}

Answered By – Matthias

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published