0

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);
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer it is work now. and I find forth solution. we can use the lazyPut too. so each to the page controller delete from memory and when back to that page create again, for example: Get.lazyPut<HomeScreenController>(() => HomeScreenController(),fenix: true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.