首页 > 解决方案 > 使用 StateNotifier Riverpod 上的方法来更改布尔值

问题描述

这是类,我想更改布尔选择。

class EleccionConSleccionClase {
      String eleccion;
      bool selec;
    
      EleccionConSleccionClase({
        required this.eleccion,
        this.selec = true,
      });
    }

我之前有一个班级列表,想显示它,而我只能选择其中一个。为此,我有一个 StateNotifier(该列表来自另一个 List,但它有效......)。我使用 CambiarSeleccion() 方法仅将我想要的更改为 true。

class EleccionesConSeleccionNotifier
    extends StateNotifier<List<EleccionConSleccionClase>> {
  final List<EleccionSinSeleccionClase> ListaElecciones;

  EleccionesConSeleccionNotifier({required this.ListaElecciones}) : super([]);

  void init() {
    if (ListaElecciones.length != 0) {
      for (int i = 0; i < ListaElecciones.length; i++) {
        state = ListaElecciones.map(
            (cb) => EleccionConSleccionClase(eleccion: cb.eleccion)).toList();
      }
    }
  }

  void CambiarSeleccion(String nombre) {
    if (ListaElecciones.length != 0) {
      for (int i = 0; i < ListaElecciones.length; i++) {
        if (state[i].eleccion == nombre) {
          state[i].selec = true;
        } else {
          state[i].selec = false;
        }
      }
    }
  }
}

final eleccionConSleccionStateNotifierProvider = StateNotifierProvider<
    EleccionesConSeleccionNotifier, List<EleccionConSleccionClase>>((ref) {
  final eleccioneswatch =
      ref.watch(eleccionesSinSeleccionStateNotifierProvider);

  return EleccionesConSeleccionNotifier(ListaElecciones: eleccioneswatch)
    ..init();
});

当我触摸按钮时 state.selec 会发生变化,但 UI 不会使用新值更新。

    class EleccionesList extends ConsumerWidget {
      @override
      Widget build(BuildContext context, ScopedReader watch) {
        final eleccioneswatchCon = watch(eleccionConSleccionStateNotifierProvider);
        return Column(
          children: [
            ListView.builder(
                shrinkWrap: true,
                physics: ScrollPhysics(),
                itemCount: eleccioneswatchCon.length,
                itemBuilder: (context, index) {
                  return Row(
                    children: [
                      Text(eleccioneswatchCon[index].eleccion +
                          '    ' +
                          eleccioneswatchCon[index].selec.toString()),
                      IconButton(
                        onPressed: () {                                           
context.read(eleccionConSleccionStateNotifierProvider.notifier).CambiarSeleccion(eleccioneswatchCon[index].eleccion);
                        },
                        icon: Icon(Icons.check_box),
                      )
                    ],
                  );
                }),
            const SizedBox(
              height: 40,
            ),
          ],
        );
      }
    }

标签: listflutterflutter-layoutstatriverpod

解决方案


推荐阅读