riverpod (v2) documentation包含两个很好的例子,说明如何使用Notifier或AsyncNotifier来实现TODO-list.这两个示例在功能上是等价的.
为了 Select 一个特定的细节,非异步示例包含一个如下所示的Remove方法
// Let's allow removing todos
void removeTodo(String todoId) {
// Again, our state is immutable. So we're making a new list instead of
// changing the existing list.
state = [
for (final todo in state)
if (todo.id != todoId) todo,
];
}
而异步版本如下所示
// Let's allow removing todos
Future<void> removeTodo(String todoId) async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
await http.delete('api/todos/$todoId');
return _fetchTodo();
});
}
现在我想修改异步版本,将已删除的TODO项从其内部状态中移除,而不是通过HTTP重新获取整个集合(这就是_fetchTodo所做的).我想一个实际的原因可能是实现一些像乐观更新这样的东西,但在这种情况下,这对我来说是一次学习的经历.