Flutter Slider Not Moving or Updating

For others coming here, I had a slightly different reason that the slider wasn't updating. I had the value set to a constant. Make sure that value is a variable.

This:

Slider(
  value: _myValue,
  ...
  onChanged: (newValue) => {
    setState(() => _myValue = newValue)
  },
),

Not this:

Slider(
  value: 0, //                     <-- problem
  ...
  onChanged: (newValue) => {
    setState(() => _myValue = newValue)
  },
),

Problem: In the above example, margin is not a state variable. It is a local variable inside a build method.

Fix: Move this as an instance variable.

Reason: Widgets will get rebuild only when there is a change in its state.

Code:

class _ItemDetailState extends State<ItemDetail> {
  Item item;
  var margin;

  _ItemDetailState({Key key, @required this.item}) {
    this.margin = ((item.listPrice - item.stdUnitCost)/item.listPrice)*100;
  }

  @override
  Widget build(BuildContext context) {
    //same as now
  }
}

Tags:

Flutter