异步Redux状态不变操作Skill asyncredux-actions-no-state-change

该技能用于在Flutter AsyncRedux框架中创建不改变应用状态的actions,允许执行副作用、调度其他操作或保持状态不变,关键词包括AsyncRedux、Flutter、状态管理、无状态改变、副作用操作、reduce方法、Dart编程。

移动开发 0 次安装 0 次浏览 更新于 3/19/2026

name: 异步redux-actions-无状态改变 description: 创建AsyncRedux(Flutter)操作,从reduce()返回null以不改变状态。此类操作仍可执行副作用、调度其他操作或什么都不做。

不改变状态的操作

在AsyncRedux中,从reducers返回新状态是可选的。当您不需要修改应用程序状态时,返回null以保持当前状态不变。

基本模式

当不需要修改状态时,从reduce()返回null

class MyAction extends ReduxAction<AppState> {
  AppState? reduce() {
    // 在这里执行副作用
    return null; // 状态保持不变
  }
}

条件状态更新

仅在满足某些条件时更新状态:

class GetAmount extends ReduxAction<AppState> {
  Future<AppState?> reduce() async {
    int amount = await getAmount();
    if (amount == 0)
      return null; // 不需要改变
    else
      return state.copy(counter: state.counter + amount);
  }
}

协调其他操作

调度其他操作但不直接修改状态的操作:

class InitAction extends ReduxAction<AppState> {
  AppState? reduce() {
    dispatch(ReadDatabaseAction());
    dispatch(StartTimersAction());
    dispatch(TurnOnListenersAction());
    return null; // 此操作本身不改变状态
  }
}

触发外部服务

调用外部服务而不修改应用状态:

class SendNotification extends ReduxAction<AppState> {
  final String message;
  SendNotification(this.message);

  Future<AppState?> reduce() async {
    await notificationService.send(message);
    return null;
  }
}

导航操作

作为副作用触发导航:

class GoToSettings extends ReduxAction<AppState> {
  AppState? reduce() {
    dispatch(NavigateAction.pushNamed('/settings'));
    return null;
  }
}

关键点

  1. 确实返回新状态的操作也可以执行副作用和调度其他操作。
  2. 返回类型很重要:对于同步操作使用AppState?,对于异步操作使用Future<AppState?>
  3. null表示无改变:存储保持其当前状态。

参考文献

文档URL: