I am trying to build a slider widget inside a dialog. I am using GetX, and a GetxController but the value of the slider or any other widget is not updating when I am trying to change it.
It only updates after I reopen the dialog. This is my code for the controller:
class SliderController extends GetxController {
static SliderController get to => Get.find();
var quality = 0.0.obs;
void setQuality(double quality) {
quality.value = quality;
update();
}
}
and my widget looks like this:
class SliderWidget extends StatelessWidget {
const SliderWidget ({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.8,
child: GetBuilder<SliderController>(
init: SliderController(),
builder: (ctrl) => Container(
decoration: BoxDecoration(
color: Colors.white70,
borderRadius: const BorderRadius.all(Radius.circular(16)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.25),
spreadRadius: 2,
blurRadius: 2,
),
],
),
child: Stack(
children: <Widget>[
Positioned(
right: 0,
top: 0,
child: CustomCheckBox(
value: false,
shouldShowBorder: true,
borderColor: Colors.blueGrey,
checkedFillColor: Colors.blueGrey,
borderRadius: 8,
borderWidth: 2,
checkBoxSize: 22,
onChanged: (checked) {
if (checked) {
Get.defaultDialog(
textConfirm: "Save",
textCancel: "Cancel",
content: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text("Quality (${ctrl.quality})"),
Slider(
value: ctrl.quality.value,
min: 0,
max: 100,
divisions: 100,
onChanged: (double value) {
ctrl.setQuality(value);
},
)
],
),
);
}
},
),
),
]
)
)
)
);
}
}
So, the dialog opens, I try to drag the slider around but it doesn't change. Seems like the value is saved in the controller because if I close the dialog and open it again, the slider has the new values.
I don't know how to make the controller update the value inside the dialog's slider
I am seeing you are using the wrong combination. In this case you are using observables (.obs
) in the controller, but using GetBuilder
in the widget.
Keep in mind that GetX
or Obx
is used to observe the observables (Reactive State Management). GetBuilder
is used for simple state management (Non-reactive/Non-observables).
So you can either change your variable type as normal dart types instead of Rx (.obs) in your controller like:
class SliderController extends GetxController {
static SliderController get to => Get.find();
double quality = 0.0;
void setQuality(double quality) {
this.quality = quality;
update();
}
}
Or you can use GetX
or Obx
in you widget. In that case no need to call update()
on the controller.