'GetX Controller in Stack (Flutter)

Im using GetX Controller in Screen A and navigating to the Screen B which is also a same screen with different data's but same Controller, (its a concept of navigating inside and inside the users profile in social media app - reference: Instagram)

The issue is when i navigates from Screen A to Screen B, Screen B data is fetched from the API which is totally fine, then when we clicks back button it return back to Screen A, but the Screen A data is replaced with Screen B data

Initialized controller like

 final ProfileViewController userProfileController =
      Get.put(ProfileViewController());

Navigating to screen like

Get.to(() => ScreenB());

Expecting the best solution, Thanks in Advance!



Solution 1:[1]

I did this and it worked fine, hope it helps

in main.dart

Get.create(() => ProfileViewController());

then in the view

ProfileViewController_con = Get.find();

Get.to(() => const ScreenB(), preventDuplicates: false);

Solution 2:[2]

Try to find and use GetWidget in GetX

With GetWidget, you will have a separate new controller for each widget instance.

class ProfileViewWidget extends GetWidget< ProfileViewController > {...}
...

class YourAnyScreenBindings implements Bindings {
  @override
  void dependencies() {
    Get.put(YourAnyScreenCtrl());
    Get.create(() => ProfileViewController());
  }
}
...

List<GetPage<dynamic>> getPages = [
  GetPage(
    name: '/your_any_screen',
    page: () => YourAnyScreen(),
    binding: YourAnyScreenBindings(),
  ),
]







Solution 3:[3]

Use tag with the controller

Initialize controller like

final ProfileViewController userProfileController =
  Get.put(ProfileViewController(),tag:'a_string_may_be_the_profile_id');

usage:

var controller = Get.find<ProfileViewController>(tag:'a_string_may_be_the_profile_id')

By this way, more than one profile controller can be created and accessed

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Trend74X
Solution 2 Hyungju Moon
Solution 3 Bharath