2

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 Answers4

1

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); 
  • I am trying to solve a somewhat similar problem, which is to pass a value from within main () to a class which lets me write to a local variable and then route to the appropriate page. Where do I create the actual value of test.value within main? – satchel Jul 12 '22 at 03:10
  • How are you setting the value of test.value and what is Test.to.a? – satchel Jul 12 '22 at 03:16
1

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.

0

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"
Sagnik Biswas
  • 53
  • 1
  • 7
  • Thank you. It works! Sometimes I need to use the latest values. But it isn't truly a global instance. Now, I am using Test testGlobals = Get.put(Test); in the same class file. But I still think my method might not be correct. – Sittiphan Sittisak Feb 20 '22 at 09:18
0

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?