applyMiddleware

StoreEnhancer<S> applyMiddleware<S>(

  1. List<Middleware<S>> middlewares
)

Applies middleware to the dispatch method of the store.

Middleware is the suggested way to extend functionality with custom behavior. It provides a third-party extension point between dispatching an action and the moment it reaches the reducer.

The middleware signature is:

Middleware<AppState> loggerMiddleware() => (api) => (next) => (action) {
  print('Dispatching: ${action.type}');
  next(action);
  print('Next state: ${api.getState()}');
};

final store = createStore( reducer, initialState, enhancer: applyMiddleware([loggerMiddleware()]), );

Implementation

StoreEnhancer<S> applyMiddleware<S>(List<Middleware<S>> middlewares) =>
    (createStoreFn, reducer, preloadedState) {
      final store = createStoreFn(reducer, preloadedState);

if (middlewares.isEmpty) return store;

// Create a dispatch that throws if called during middleware setup NextDispatcher dispatch = _throwingDispatch;

final middlewareApi = ( getState: store.getState, dispatch: (Action action) => dispatch(action), );

// Build the middleware chain final chain = middlewares.map((m) => m(middlewareApi)).toList();

// Compose the chain with the store's dispatch dispatch = _composeMiddleware(chain)(store.dispatch);

return _MiddlewareStore(store, dispatch); };