riverpod (v2) documentation包含两个很好的例子,说明如何使用NotifierAsyncNotifier来实现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所做的).我想一个实际的原因可能是实现一些像乐观更新这样的东西,但在这种情况下,这对我来说是一次学习的经历.

推荐答案

在没有以任何方式测试这段代码的情况下,我认为这也许能够达到目的.

问题在于API调用中的错误处理,以及这将如何影响将新的过滤状态分配给实际的AsyncNotifier状态.为此,您可能希望使用try/Catch来包装API调用,或者根据来自服务器的响应采取操作.

  Future<void> removeTodo(String todoId) async {
    // We need the original state, but with the todo removed.
    final filteredState = [
      for (final todo in state.requireValue)
        if (todo.id != todoId) todo,
    ];

    // With the correct new state now saved in a local variable, set the loading value to the state.
    state = const AsyncValue.loading();

    // Perform delete
    await http.delete('api/todos/$todoId');

    // Set the value of the new filtered state to our state
    // Note: we do need to assign this value with an assign action, because of the immutable nature of the state.
    state = AsyncValue.data(filteredState);
  }

Flutter相关问答推荐

如何增加容器高度?

壁炉有序在Flutter

Flutter API请求BadState响应

来自FirebaseAuth的错误DisplayName和邮箱在Flutter应用程序中给出错误

从图标启动器打开时,VSCode未检测到Web设备

按一下按钮即可更新 fl_chart

如何在点击查看措辞下方添加句子?

SliverAppbar 呈蓝色

Flutter Dismissible 不会在 startToEnd 滑动时被关闭

Flutter ListView 在调用 setState 后未更新

围绕父组件旋转位置组件

Android 模拟器在 Apple M2 芯片 EXC_BAD_ACCESS / KERN_INVALID_ADDRESS 上随机崩溃

为什么我们使用 RiverpodGenerator

如何(部分)更新 riverpod 中的 AsyncValue?

flutter 创建一个带有 2 个图标的按钮

如何根据字符串值动态构建和显示小部件?

如何在 flutter 中制作这种类型的扩展瓦片

如何使按钮被选中?

有没有办法帮助我修复类型 null 不是 Map 类型的子类型?

如何在 ElevatedButton 上设置背景 colored颜色 动画?