How can I use the Slider Widget with GetX/Obx?
class Slider1 extends StatelessWidget {
const Slider1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
SliderController sx = Get.put(SliderController());
return SizedBox(
child: Column(children: [
Obx(
() => Slider(
value: sx.range,
min: 0,
max: 255,
divisions: 255,
label: sx.range.round().toString(),
onChanged: (double value) {
sx.setRange(value);
},
),
)
]),
);
}
}
class SliderController extends GetxController {
double range = 255.obs as double;
void setRange(double range) {
this.range = range;
}
}
Like this i get,
_CastError (type 'RxInt' is not a subtype of type 'double' in type cast)
CodePudding user response:
According to your way of implementing, The only Mistake was in the initialization of the variable. Bellow changes would make it work.
Obx(
() => Slider(
value: sx.range.value,
min: 0.0, //initialized it to a double
max: 255.0, //initialized it to a double
divisions: 255,
label: sx.range.round().toString(),
onChanged: (double value) {
sx.setRange(value);
},
),
)
Changes in the controller.
class SliderController extends GetxController {
Rx<double> range = 255.0.obs; //again initialized it to a Rx<double>
void setRange(double range) {
this.range.value = range; //updating the value of Rx Variable.
}
}
CodePudding user response:
Meanwhile i was trying a different approach
class SliderText extends StatelessWidget {
const SliderText({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
child: GetBuilder<SliderController>(
init: SliderController(),
builder: (ctrl) => SizedBox(
child: Text('Sliding Value: ${ctrl.range}'),
),
),
);
}
}
//--------------------------------------------------------------
class SliderController extends GetxController {
static SliderController get to => Get.find();
double range = 255;
void setRange(double range) {
this.range = range;
update();
}
}
@Krish Bhanushali, which one it is better?