Search code examples
flutterdartflutter-layoutflutter-animation

How to update a slider's value with StateProvider?


Trying to set the value of a slider with a Riverpod StateProvider.

The value changes in OnChanged but the slider's value doesn't change. What am I doing wrong?

My code:

final valueProvider = StateProvider<double>(
  (ref) => 0.0,
);

class DynamicCircle extends HookConsumerWidget {
  const DynamicCircle({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    double slider = 0.0;

    final value = ref.watch(valueProvider.notifier);
    return Column(
      children: [
        Slider(
            value: value.state,
            max: 2.0,
            min: 0.0,
            onChanged: (value) {
              print(value);
              ref.read(valueProvider.notifier).state = value;
            }),
        Text(value.state.toString())
      ],
    );
  }
}

Solution

  • to rebuild your ui and reflect the changes, you have to use 'ref.watch(valueProvider.state).state;'

    try this out.

    final valueProvider = StateProvider<double>(
      (ref) => 0.0,
    );
    
    class DynamicCircle extends HookConsumerWidget {
      const DynamicCircle({super.key});
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        double slider = 0.0;
    
        final value = ref.watch(valueProvider.state).state;
        return Column(
          children: [
            Slider(
                value: value.state,
                max: 2.0,
                min: 0.0,
                onChanged: (value) {
                  print(value);
                  ref.read(valueProvider.notifier).state = value;
                }),
            Text(value.toString())
          ],
        );
      }
    }