Nicolas
Nicolas

Reputation: 3

Flutter Slider, How to limit the possible input?

Let's imagine the following: I have two Sliders, each can get input from 0 to 10. But both together should also be limited to a max Input of 10.

So if the first Slider is set to 6, I want the second Slider to just allow Inputs from 0 to 4. But still, show the full Slider with 10 Divisions. The right side of the second Slider (5 to 10) should just be not settable for the User.

How can I achieve this? Thanks a lot!

Upvotes: 0

Views: 1763

Answers (2)

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12713

Check this out

class TwoSliders extends StatefulWidget {
  @override
  _TwoSlidersState createState() => _TwoSlidersState();
}

class _TwoSlidersState extends State<TwoSliders> {
  double slider1 = 0;
  double slider2 = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Slider(
              onChanged: (value) {
                if((value+slider2)<=10){
                  setState(() {
                    slider1 = value;
                  });
                }
              },
              max: 10,
              divisions: 10,
              value: slider1,
              label: slider1.toString(),
            ),
            Slider(
              onChanged: (value) {
                if((value+slider1)<=10){
                  setState(() {
                    slider2 = value;
                  });
                }
              },
              value: slider2,
              max: 10,
              divisions: 10,
              label: slider2.toString(),
            ),
          ],
        ),
      ),
    );
  }
}

The Output:

enter image description here

Upvotes: 3

MickaelHrndz
MickaelHrndz

Reputation: 3842

In both of the onChanged() callbacks, only update the value if it is inferior or equal to 10 minus the value of the other Slider.

Upvotes: 0

Related Questions