Search code examples
flutterdartflutter-getx

Flutter Getx argument is never reset


I am working with flutter and trying to use Getx package for passing arguments between components and my problem is that the arguments are never put to null after use. As the component i am navigating to's view depend on these argument i read, i don't have the right after one argument passing. To explain : navigate this way

 Get.offAll(() => Home(), arguments: 1);   <==== arguments represents an initial tab Index in Home

then in Home

 DefaultTabController(
      initialIndex: Get.arguments?? 0, <=== Get.arguments is never null again after line executed once
      length: tabs.length,

Generally arguments are no more null in any other Widget even if i navigate to without passing arguments

I know i could directly use the constructor to pass the value but i simplified the case.

So what am i missing? I searched a lot and logically in my head i don't understand how to reset the arguments

Thanks for any help


Solution

  • since Get.arguments is a getter not a setter, you cannot change it's value like this:

    Get.arguments = null; // you can't do this
    

    however, I see that you're trying to use the Get.arguments only once and then, you want it to behave like it's null, right?

    So instead of using Get.arguments directly, store it in another variable, then use that variable in the initialIndex property like the following.

    inside the class add this static count variable:

    static int useCount = 0;
    

    we will track how many times we tried to use Get.arguments.

      dynamic argumnetsMangedByUseCount() {
          if (useCount >= 1) {
            return null;
          }
          useCount++;
        
          return Get.arguments;
        }
    

    instead of Get.arguments, we will use this method so it returns either null or Get.arguments based on useCount.

    the 1 number represents the max allowed times that it should return Get.arguments, otherwise it will return null.

    Finally, in your DefaultTabController :

    DefaultTabController(
      initialIndex: argumnetsMangedByUseCount() ?? 0,
      length: tabs.length,
    

    now after you have a hot restart for the app, you will get the Get.arguments only once, after that you will get null on it.