As the title reads, there are a couple of ways to update state. When should I choose one over another?
There's no hard rules about this, but here's how I try to decide:
initState calls during creation and I wantUnder the hood, both Obx and GetX use streams, subscribing to controller observable variables change streams to know when to reactively rebuild.
GetBuilder does not.
GetX and GetBuilder both extend StatefulWidget
In the GetX package there are two ways to write controller:
First:
class Controller extends GetxController {
int counter = 0;
void increment() {
counter++;
update();
}
}
This is called Simple State Manager. It uses a simple callback to notify the consumer widget. And that widget can only be GetBuilder.
GetBuilder<Controller>(
builder: (controller) => Text(
'${controller.counter}',
),
)
GetBuilder is super performance-friendly. It should be used wherever possible.
The second way to write controller:
class Controller extends GetxController {
var count = 0.obs;
increment() {
count.value++;
//refresh();
}
}
This is called Reactive State Manager. It uses streams under the hood. Streams are great but they consume a lot of resources.
To consume this kind of state we need Obx or GetX.
Obx example:
child: Obx(
() => Text(
'${controller.counter}',
),
),
The Obx cannot be parameterized with the controller type so to get a controller instance we should use GetView or GetWidget or StatelessWidget with Get.find.
This is where the GetX widget comes in help.
GetX example:
GetX<Controller>(
init: Get.put<Controller>(Controller()),
builder: (controller) {
return Text( '${controller.counter}');
},
)
The difference between Obx and GetX is that GetX has init and builder properties. Also, GetX can be parameterized with controller type. The init property is optional. It is only required in case the controller was not yet initialized.
Conclusion Use GetBuilder whenever possible. It is very performance-friendly. 👍 Use Obx and GetX only when you have to. Use Obx with GetView or GetWidget or Get.find. Use GetX when you want to initialize the controller directly inside the widget. From this article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With