flutter - Flutter/Riverpod:UI 不更新 StateNotifierProvider 中的状态更改
问题描述
当我知道状态正在改变的事实时,我的应用程序的 UI 没有更新。我正在使用watch
Riverpod 的方法来处理这个问题,但除非我进行热重载,否则更改不会生效。
我有一个类HabitListStateNotifier
,其中包含从列表中添加/删除习惯的方法:
class HabitListStateNotifier extends StateNotifier<List<Habit>> {
HabitListStateNotifier(state) : super(state ?? []);
void startAddNewHabit(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (_) {
return NewHabit();
});
}
void addNewHabit(String title) {
final newHabit = Habit(title: title);
state.add(newHabit);
}
void deleteHabit(String id) {
state.removeWhere((habit) => habit.id == id);
}
}
这是提供者:
final habitsProvider = StateNotifierProvider(
(ref) => HabitListStateNotifier(
[
Habit(title: 'Example Habit'),
],
),
);
以下是HabitList
(未更新的 UI 部分)的实现方式:
class HabitList extends ConsumerWidget {
@override
Widget build(BuildContext context, ScopedReader watch) {
final habitList = watch(habitsProvider.state);
/////////////not updating/////////////
return ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
return HabitCard(
habit: habitList[index],
);
},
itemCount: habitList.length,
);
/////////////not updating/////////////
}
}
最后,HabitCard
(由什么HabitList
组成):
class HabitCard extends StatelessWidget {
final Habit habit;
HabitCard({@required this.habit});
@override
Widget build(BuildContext context) {
/////////////function in question/////////////
void deleteHabit() {
context.read(habitsProvider).deleteHabit(habit.id);
}
/////////////function in question/////////////
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(devHeight * 0.03),
),
color: Colors.grey[350],
elevation: 3,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
HabitTitle(
title: habit.title,
),
Consumer(
builder: (context, watch, child) => IconButton(
padding: EdgeInsets.all(8),
icon: Icon(Icons.delete),
/////////////function in question/////////////
onPressed: deleteHabit,
/////////////function in question/////////////
),
),
],
),
],
),
);
}
}
当我按下 a 中的删除图标时HabitCard
,我知道Habit
它已从列表中删除,但更改并未反映在 UI 中。但是,当我进行热重载时,它会按预期消失。我在这里做错了什么?
解决方案
我不知道这是否是处理事情的正确方法,但我想通了。在HabitListStateNotifier
, foraddNewHabit
和deleteHabit
中,我将这行代码:添加到最后:state = state;
它完全按照我想要的方式工作。
推荐阅读
- csv - 将 CSV 文件转换为 Siddhi 事件
- kubernetes-helm - 如何在 Helm 图表中将字符串化的 json 值作为参数/变量?
- android - 在颤动地图视图中单击导航图标时,在谷歌地图中的两个标记之间显示方向
- c++ - lambda中的noexcept如何在vs2012中工作?
- json - 架构 - 星级从谷歌消失:“评论没有指定名称的评论项目”
- python - 如何使用 Tensorflow 增强树进行图像分类任务?
- mongoose - Mongoose 子文档查询仅返回 id?
- javascript - JavaScript 函数 - 计算对象数组中某个值的出现次数
- amazon-web-services - 使用 AWS ELB 为带有自定义 ACM 证书的 HTTPS 流量配置 Istio Ingress
- reactjs - 在 React Native 上无缘无故的 Foursquare API 错误请求