0

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,
        ),
      ],
    );
  }
}
1
  • Cant find eleccionesSinSeleccionStateNotifierProvider Commented Aug 12, 2021 at 1:13

1 Answer 1

1

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;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.