Flutter Getx: Can obs create a global variable?

Viewed 1171

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); //""
4 Answers

You can insert your class into main with Get.put(Test()); and it would be something like:

void main() {
  Get.put(Test());
  runApp(...);
}

In your test class add the following code: static Test get to => Get.find<Test>();

Your Test class would look like this:

class Test extends GetxController {
 static Test get to => Get.find<Test>();
  RxString a = "".obs;
}

Now you have your global class and to send it to call it would be as follows:

Test.to.a

You would use it in the following way:

//IMPORT TEST CLASS
//get the same instance that has already been created
Test test =  Test.to.a; 
print(test.value); 

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"

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?

Update Now, I am using

Class + static

Class:

Class Global {
     static Rx<String> name = "me".obs;
     static ProfileObject profile = ProfileObject();
}

Use:

Obx(()=>Text(Global.name.value)),
Obx(()=>Text(Global.profile.age.value)),

It is easy to use, don't setting just use static in class.

Related