The GetBuilder Widget
Learn to handle state updates manually with GetBuilder.
Overview
GetBuilder is a wrapper widget used to listen to the changes made inside a controller. Whenever we call the update()
method inside the controller, the corresponding GetBuilder rebuilds. Simple as that! Here’s how we wrap a widget with GetBuilder:
GetBuilder<Controller>(init: Controller(),builder: (controller) => Text(controller.name),);
Let’s go through the syntax line by line:
Line 1: We provide the
Controller
type to the GetBuilder. This connects our widget to the specified controller.Line 2: We initialize the controller by providing the
Controller()
instance to theinit
parameter.Line 3: We have the
builder
parameter to build our widget usingcontroller
.
Something to note here is that we do not have to initialize the controller with every single GetBuilder. We do that only the first time we use it and all other GetBuilders of the same type will use the same instance of the controller. Here's what we mean by that:
GetBuilder<Controller>(init: Controller(),builder: (controller) => Text(controller.name),);GetBuilder<Controller>(builder: (controller) => Text(controller.age),);GetBuilder<Controller>(builder: (controller) => Text(controller.mood),);
Life cycle controls
At its core, GetBuilder is nothing but a StatefulWidget. Hence, it offers complete control over its life cycle, i.e., the sequence of stages or events that the widget goes through during its existence within a Flutter application. We get access to all the life cycle methods, namely initState
, didUpdateDependencies
, didUpdateWidget
, and dispose
.
GetBuilder<Controller>(initState: (state) {// Called as soon as widget is initialized.},didChangeDependencies: (state) {// Called right after initState and whenever dependencies of the widget change.},didUpdateWidget: (oldWidget, state) {// Called every time the widget is rebuilt.}dispose: (state) {// Called right before the widget is disposed.});
Now having access ...