list - 使用 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,
),
],
);
}
}
解决方案
推荐阅读
- circleci - 在 CircleCI 中为不同环境设置环境变量
- redis - redis-sentinel 支持会结束吗?
- postgresql - 社交网络的架构设计建议
- ios - 从 Firebase 检索数据需要很长时间
- mysql - redmine:项目和联系人(公司)的sql关系是什么
- google-sheets - 查看者(每个链接)在打开文件时跳转到当前日期
- ruby - main:Object 的未定义方法“lane”
- java - 如何启动 Java NMT
- android - TextAppearance.MaterialComponents.Body2 的定义?
- ios - React Native iOS 应用在 App Purchase 中被拒绝