0

So I'm using this stateNotifierProvider in order to keep track of the selectedItem in this toggleButton, however even if the state of the notifier is in fact changed, it does not trigger the build function as it should... Can anyone help me with this one?

Thanks!

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../../global/theme/theme_data.dart';

final sexProvider =
    StateNotifierProvider<SexNotifier, List<bool>>((ref) => SexNotifier());

class SexNotifier extends StateNotifier<List<bool>> {
  SexNotifier() : super([false, false, false]);

  void updateSex(int index) {
    List<bool> newState = state;
    for (int i = 0; i < newState.length; i++) {
      if (i == index) {
        newState[i] = true;
      } else {
        newState[i] = false;
      }
    }
    state = newState;
  }
}

class SexPicker extends ConsumerWidget {
  const SexPicker({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final List<bool> selectedIcon = ref.watch(sexProvider);

    return ToggleButtons(
        selectedColor: Theme.of(context).primaryColor,
        fillColor: ThemeModeData.kRedAccentColor,
        borderRadius: BorderRadius.circular(22),
        isSelected: selectedIcon,
        onPressed: (index) {
          ref.read(sexProvider.notifier).updateSex(index);
        },
        children: const [
          Icon(
            Icons.man,
            size: 60,
          ),
          Icon(Icons.woman, size: 60),
          Icon(Icons.transgender_outlined, size: 50),
        ]);
  }
}

I tried everything I could to make it work but can't find any answer.

zatheg
  • 1
  • 2

1 Answers1

0

your new state needs to be a new object as state is meant to be immutable. You must create a new instance if you want to change it.

instead of state = newState;, do state = newState.toList(); which will create a new List.

Madushan
  • 6,977
  • 31
  • 79