Search code examples
androidfluttercontrollerflutter-getx

how to reload getx controller?


hi I try using Getx Controller in flutter. I want my oninit of controller reload and set the new data each time user go two my certain page, but only the first time page reload oninint excute. how can I set onInit reload each time user go to this page?

my onInit code is:

@override
Future<void> onInit() async {
  super.onInit();
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  name = (sharedPreferences.getString('name') ?? '-1').obs;
  avatarImage = (sharedPreferences.getString('imageAddress') ?? '-1').obs;
  username = sharedPreferences.getString('username') ?? '-1';
  file = File(avatarImage.value);
}

Solution

  • Since the controllers aren't named, I will say that we have a ReloadedController which contains the onInit() in your code snippet, and we have the SpecificPageController that belongs to that specific page.

    I can think of two solutions that will suit your case:

    First sulution: delete the controller and inject it again, to execute the onInit():

    class SpecificPageController extends GetxController {
      @override
      void onInit() {
        Get.delete<ReloadedController>();
        Get.put(ReloadedController());
        super.onInit();
      }
    }
    

    This will delete the ReloadedController from the memory, then inject it again, this will trigger the OnInit() to execute since we just injected it.

    Second solution: forcefully execute the onInit() method:

    class SpecificPageController extends GetxController {
      @override
      void onInit() {
        Get.find<ReloadedController>().onInit();
        super.onInit();
      }
    }
    

    This will execute forcefully the OnInit() method, which will behave like a reload for your onInit() code every time the specific page will be opened.

    Third, solution: using onGenerateRoute

    return GetMaterialApp(
      onGenerateRoute: (settings) {
        if (settings.name == "/yourSpecificPageRoure") {
          name = (sharedPreferences.getString('name') ?? '-1').obs;
          avatarImage =
              (sharedPreferences.getString('imageAddress') ?? '-1').obs;
          username = sharedPreferences.getString('username') ?? '-1';
          file = File(avatarImage.value);
        }
      },
    // ...
    

    Change /yourSpecificPageRoure with your route path name.

    This method is called every time a route is generated in your app, the price of your code will be executed only when the route name is /yourSpecificPageRoure.