简体   繁体   English

使用带有 GetX/Obx 的 Slider 小部件

[英]Using a Slider widget with GetX/Obx

How can I use the Slider Widget with GetX/Obx?如何将 Slider 小部件与 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) _CastError(类型'RxInt'不是类型转换中类型'double'的子类型)

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. 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. 
  }
}

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? @Krish Bhanushali,哪个更好?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM