Search code examples
flutterdartflutter-getx

How to reset variable to default values in getx?


I am creating an app that has multiple questions (like a quiz) and I am using Getx for state management.

in the main method I initialize controllers as follows

void main() {
  Get.put(HomeScreenController());
  Get.put(QuestionsController());
  runApp(MyApp());
}

in the home screen I have a pageview and I am using HomeScreenController() to manage it. The last page of the page view has a button to go back to the initial page. For my case, I want to reset all variables in both controllers to their initial values.

I have tried one solution, it worked but I feel like it is tedious to do for other controllers that has so many variables which is calling a method that reset the variables manually.

The other solution that I have tried is to dispose the controllers when the user clicks on the button calling Get.put(HomeScreenController()); in the build method of the home screen.

onPressed: () {
                    qCon.dispose();
                    controller.dispose();
                    Navigator.pushReplacementNamed(context, HomeWrapper.id);
                  },

but I got an error that says

A HomeScreenController was used after being disposed.

'Once you have called dispose() on a HomeScreenController, it can no longer be used.

is there anyway to do what I am trying to do other than updating variable manually?


Solution

  • Update: Turns out that

    Get.reset();
    

    do the job when initializing controllers in the home screen

    also calling

    Get.put(ControllerName());
    

    in a build method will re-initialize the controller