0

am playing around with the slider widget on flutter, and I can't figure out why it does not update certain values in a different widget, example code is shown below;

When i move the slider, it has no issues moving, but the value i'm trying to update on the other widget does not update even though the onchanged is updating the variable passed through in a set state accordingly.

any help would be greatly appreciated!

Scaffold Code

class TestPage extends StatelessWidget {
  static const id = "test_page";

  @override
  Widget build(BuildContext context) {
    double testValue = 0;

    return Scaffold(
      body: Column(
        children: [
          Text("Hello World"),
          TestBoxNumber(
            numberDisplay: testValue,
          ),
          TestSlider(testValue: testValue),
        ],
      ),
    );
  }
}

Slider Code

class TestSlider extends StatefulWidget {
  double testValue;

  TestSlider({required this.testValue});

  @override
  _TestSliderState createState() => _TestSliderState();
}

class _TestSliderState extends State<TestSlider> {
  @override
  Widget build(BuildContext context) {
    return Slider(
      activeColor: themeData.primaryColorLight,
      value: widget.testValue,
      min: 0,
      max: 100,
      divisions: 100,
      label: widget.testValue.round().toString(),
      onChanged: (double value) {
        setState(() {
          widget.testValue = value;
        });
      },
    );
  }
}

Different Widget Code

class TestBoxNumber extends StatefulWidget {
  final double numberDisplay;

  const TestBoxNumber({required this.numberDisplay});

  @override
  _TestBoxNumberState createState() => _TestBoxNumberState();
}

class _TestBoxNumberState extends State<TestBoxNumber> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.numberDisplay.toString()),
    );
  }
}

1 Answers1

1

The problem is that you are constructing TestBoxNumber widget in such a way that value (testValue) will always be the same (testValue is never returned out of the TestSlider widget).

How to overcome this issue?

You can make your TestPage a StatefullWidget. Then create callback from TestSlider, so when you change value in TestSlider you will call some function in TestPage (with setState in it, causing re-rendering your page).

Or if you don't want your whole TestPage widget to be Statefull (if, let's say, you predict a lot of other static widgets in it and you don't want them to be re-rendered because you just moved a slider), you can create wrapper Statefull widget and put both TestSlider and TestBoxNumber widgets in it. This is more flexible approach, imho.

Here is small scheme of what I mean by wrapping two widgets in another one: enter image description here

UPD: btw, there is no point in making TestBoxText a statefull widget if it's only purpose is to display a text and you pass it's value through the constructor.

obywan
  • 854
  • 8
  • 14