Core concepts

Reducer

The following is an exploration of what a Reducer is conceptually and how they are used in Flutter Forge.


Concept

A Reducer conceptually, within the world of Flutter Forge, is simply a thing that is responsible for interpreting Actions and computing change to State.

In Practice

In the world of Flutter Forge a Reducer can basically be thought of as a function responsible for taking in the current State as well as an Action and return what the new State should be as well as an Array of zero or more Effects.

final counterReducer = Reducer<CounterWidgetState, CounterWidgetEnvironment, CounterWidgetAction>(
    (state, action) {
  switch (action) {
  	case CounterWidgetIncrementButtonTapped _:
      return ReducerTuple(CounterWidgetState(count: state.count + 1), []);
  }
});

In the above example we have a simple Reducer for the Counter Component. It takes in Actions and checks if the action is a CounterWidgetIncrementButtonTapped action. If it is then it returns a ReducerTuple containing a newly constructed instance of the CounterWidgetState with a count equal to the previous count, plus one. It also includes an empty Array of Effects since there are no side effects triggered by this Action.

The Reducer is a dependency of a Store and has to be passed into the Store during construction.

Dart < 3.0

If you are using a version of Dart less than 3.0 then your Base Action won't be able to be a sealed class and will instead have to be a abstract class. Because of this you won't have the pattern matching available at compile time to make sure you have handled all the cases. So the best you can do is runtime checks of the action types as follows and then provide a else block with a noop.

final counterReducer = Reducer<CounterWidgetState, CounterWidgetEnvironment, CounterWidgetAction>(
    (state, action) {
  if (action is CounterWidgetIncrementButtonTapped) {
    return ReducerTuple(CounterWidgetState(count: state.count + 1), []);
  } else {
    return ReducerTuple(state, []);
  }
});

We strongly encourage you to upgrade your projects to Dart 3.0 or above as it is a much nicer world to live in.

Previous
Actions