Home > database >  Flutter Getx: Can obs create a global variable?
Flutter Getx: Can obs create a global variable?

Time:02-21

How to make obs a global variable?

Have an option of Getx that can create a global variable?

For the example:

class Test extends GetxController {
  RxString a = "".obs;
}

Page 1:

Test test =  Get.put(Test());
print(test.a.value); //""
test.a.value = "55555";
print(test.a.value); //"55555"

Page 2:

Test test =  Get.put(Test());
print(test.a.value); //""

CodePudding user response:

Get.put() creates single instances, however, if you want to create a global controller, there's Get.find() which fetches the last instance of the controller created and shares it, that way global access can be achieved.

You can read more about this here

Note, to use Get.find(), an instance needs to be created earlier.

Your new code will look like this:

class Test extends GetxController {
  RxString a = "".obs;
}

Page 1:

Test test =  Get.put(Test());
print(test.a.value); //""
test.a("55555");
print(test.a.value); //"55555"

Page 2:

Test test =  Get.find<Test>();
print(test.a.value); //"55555"

CodePudding user response:

If your work needs the latest value you can follow the comment of @Sagnik Biswas. It works!

Now, I am using basic globals instances.

test_cont.dart:

TestCont testContGlobals =  Get.put(TestCont());
class TestCont extends GetxController {
  RxString a = "".obs;
}

But I still think my method might not be correct.

Are there any disadvantages to this method?

  • Related