Search⌘ K
AI Features

The ValueBuilder and ObxValue Widgets

Explore how to manage local widget state in Flutter using GetX's ValueBuilder and ObxValue widgets. This lesson shows you to update UI elements like switches and text fields reactively without needing manual state variables or setState, streamlining your state management process with practical code examples.

Introduction

ValueBuilder and ObxValue are stateful widgets that control the local state of the widget they wrap around. Consider we have a switch; we can control its toggle state simply by wrapping it with one of these widgets. There is no need to create a variable or a toggle method with setState. This helps us classify the code for widgets whose state can be defined by a single variable.

ValueBuilder

ValueBuilder is a local state manager that defines a widget’s state using a single variable and provides the mechanism to update it. If the variable’s value changes, it updates the state and rebuilds the widget.

Let’s look at its syntax:

Dart
ValueBuilder<bool?>(
initialValue: false,
builder: (snapshot, updater) => Switch(value: snapshot!, onChanged: updater),
)

ValueBuilder takes the type of the value and has the initialValue parameter, where we specify the initial value to be used. builder is a function with two parameters—snapshot and updater. snapshot is the latest snapshot of the value, and updater is the function responsible for rebuilding the widget. ...