Diego jiménez
Diego jiménez

Reputation: 47

Flutter UI doesn't update with changes on StateNotifier

I want to create a list o buttons with text so that the user can select one of them.

For the state of the buttons I used a StateNotifier:

class SeleccionStateNotifier extends StateNotifier<List<bool>> {
  int cantidad;

  SeleccionStateNotifier(this.cantidad)
      : super(List.generate(cantidad, (index) => false));

  void CambioValor(int indice) {
    for (int i = 0; i < cantidad; i++) {
      if (i == indice) {
        state[i] = true;
      } else {
        state[i] = false;
      }
    }
  }
}

final seleccionProvider =
    StateNotifierProvider<SeleccionStateNotifier, List<bool>>((ref) {
  final lector = ref.watch(eleccionesSinSeleccionStateNotifierProvider);
  return SeleccionStateNotifier(lector.length);
});

Now in the UI I just want to show a text and the value of the button (false for everyone except the one the user selects)

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

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    bool este = false;
    final eleccioneswatchCon =
        watch(eleccionesSinSeleccionStateNotifierProvider);
    final seleccionwatch = watch(seleccionProvider);
    final buttons = List<Widget>.generate(
      eleccioneswatchCon.length,
      (i) => Container(
        padding: const EdgeInsets.fromLTRB(5, 2, 5, 2),
        child: TextButton(
          onPressed: () {
            context.read(seleccionProvider.notifier).CambioValor(i);
            print('OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO');
            for (int id = 0; id < eleccioneswatchCon.length; id++) {
              print(seleccionwatch[id]);
            }
          },
          child: Text(eleccioneswatchCon[i].eleccion + ' ' + seleccionwatch[i].toString()),
        ),
      ),
    ).toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Wrap(
          alignment: WrapAlignment.spaceAround,
          children: buttons,
        ),
      ],
    );
  }
}

Upvotes: 0

Views: 416

Answers (1)

EdwynZN
EdwynZN

Reputation: 5601

based on my previous answer you should update state itself, not an inner value of a list to take effect

void CambioValor(int indice) {
    final list = List.of(state);
    for (int i = 0; i < cantidad; i++) {
      if (i == indice) {
        list[i] = true;
      } else {
        list[i] = false;
      }
    }
    /// it will update when you use the setter of state
    state = list;
  }

Upvotes: 1

Related Questions