Fluter : How can I change variable with Getx?

Issue

I want to change the value of counter to 0 .
But everytime i try, its 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

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

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