Flutter:使用开关将滑块值设置为 0

Flutter: Use switch to set slider value to 0

我有以下代码。 我想使用开关,当转动 off/false 将滑块值设置为 0 但将滑块保持在原来的位置,所以当开关转动 on/true 时,滑块的输出值 returns 到它的原始值。

第一次来这里学习,所以请温柔。

 mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            SfRadialGauge(
              axes: <RadialAxis>[
                RadialAxis(
                    minimum: -10,
                    maximum: 60,
                    interval: 10,
                    pointers: <GaugePointer>[
                      RangePointer(
                        value: 28,
                        enableAnimation: true,
                      )
                    ],
                    annotations: <GaugeAnnotation>[
                      GaugeAnnotation(widget: Text("28"))
                    ])
              ],
            ),
            Text("LED"),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Switch(
                    value: switchstate,
                    onChanged: (bool s) {
                      setState(() {
                        switchstate = s;
                        print(switchstate);
                      });
                    }),
                Slider(
                  value: sliderval,
                  onChanged: (sliderval) => setState(
                    () => this.sliderval = sliderval,
                  ),
                  min: 0,
                  max: 100,
                ),
              ],
            ),
          ],

试试这个:

Slider(

// if you want it to always show the value, use this.
// value: sliderval,

//if you want it ZERO if it's turned off, and show a value only when it's on[Better UX].
value: switchState ? sliderval : 0, //This will check if switchState is true first. It's called a ternary operator.
onChanged: (value) => setState(
() => sliderval = value,
),

与其在开关关闭时将值更改为 0,不如直接禁用它,这样用户在开关关闭之前无法使用滑块,这样滑块将保持在原位,只是用户将无法使用滑块。

如果您仍想随心所欲,请尝试以下代码。


Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Switch(
                    value: switchstate,
                    onChanged: (bool s) {
                      setState(() {
                        switchstate = s;
                        print(switchstate);
                      });
                    }),
                Slider(
                  value: switchState == true ? sliderval : 0,
                  onChanged: (sliderval) => setState(
                    () => this.sliderval = sliderval,
                  ),
                  min: 0,
                  max: 100,
                ),
              ],
            ),

注意: switchState == true ? sliderval : 0 在滑块小部件上,它检查开关是否打开,它显示滑块值,否则它显示 0.