Problem Statement
How do you implement Redux pattern in Flutter? Explain actions, reducers, store, and middleware.
Explanation
Define actions as simple classes representing events, like class IncrementAction or class FetchUserAction { final String userId; }. Actions are dispatched to the store describing what happened. They're immutable and may contain payload data. Use action types or classes to distinguish actions, with classes being more type-safe and maintainable.
Create reducers as pure functions taking current state and action, returning new state without mutations. Combine multiple reducers handling different parts of state tree using combineReducers. For example, appReducer combines counterReducer, userReducer, etc. Reducers must be pure - same inputs always produce same outputs with no side effects, enabling time-travel debugging and predictability.
Create store with Store<AppState>(reducer: appReducer, initialState: AppState.initial(), middleware: middleware). Wrap app with StoreProvider<AppState>(store: store, child: MyApp()) to provide store to the tree. Use StoreConnector<AppState, ViewModel> to connect widgets to store, mapping state to view model and dispatching actions. StoreConnector only rebuilds when relevant state changes based on distinct property.
Middleware intercepts actions before they reach reducers for side effects like async operations, logging, or analytics. Middleware is a function receiving store, action, and next, optionally dispatching other actions. Use middleware for async operations - intercept action, perform async work, then dispatch success or failure actions. Redux pattern ensures predictable state management with clear data flow, valuable for complex apps but involves substantial boilerplate compared to simpler solutions.

