Question #215EasyState Management

What is redux ? what is the use of redux and how it is different from state managements and provide me some sample code/architechture of redux

#state

Answer

Overview

Redux is a predictable state management pattern where the entire app state lives in a single store, and all state changes happen through actions dispatched to reducers.


Redux Core Concepts

text
Action → Reducer → Store → UI
  ↑                          |
  └──────────────────────────┘ (UI dispatches actions)
ConceptDescription
StoreSingle source of truth — holds all app state
StateImmutable snapshot of app data
ActionPlain object describing what happened
ReducerPure function: (currentState, action) → newState
MiddlewareSide effects (API calls, logging) between action and reducer

Flutter Redux Example

yaml
dependencies:
  flutter_redux: ^0.10.0
  redux: ^5.0.0

1. Define State

dart
class AppState {
  final int counter;
  final bool isLoading;
  final List<User> users;

  AppState({
    this.counter = 0,
    this.isLoading = false,
    this.users = const [],
  });

  AppState copyWith({int? counter, bool? isLoading, List<User>? users}) {
    return AppState(
      counter: counter ?? this.counter,
      isLoading: isLoading ?? this.isLoading,
      users: users ?? this.users,
    );
  }
}

2. Define Actions

dart
class IncrementAction {}
class DecrementAction {}
class LoadUsersAction {}
class UsersLoadedAction {
  final List<User> users;
  UsersLoadedAction(this.users);
}

3. Define Reducer

dart
AppState appReducer(AppState state, dynamic action) {
  if (action is IncrementAction) {
    return state.copyWith(counter: state.counter + 1);
  }
  if (action is DecrementAction) {
    return state.copyWith(counter: state.counter - 1);
  }
  if (action is UsersLoadedAction) {
    return state.copyWith(users: action.users, isLoading: false);
  }
  return state;
}

4. Create Store and Provide

dart
void main() {
  final store = Store<AppState>(
    appReducer,
    initialState: AppState(),
    middleware: [thunkMiddleware],
  );

  runApp(StoreProvider<AppState>(
    store: store,
    child: MyApp(),
  ));
}

5. Connect UI

dart
// StoreConnector maps store state to widget props
StoreConnector<AppState, int>(
  converter: (store) => store.state.counter,
  builder: (context, counter) => Text('Count: $counter'),
)

// Dispatch action
StoreConnector<AppState, VoidCallback>(
  converter: (store) => () => store.dispatch(IncrementAction()),
  builder: (context, increment) => ElevatedButton(
    onPressed: increment,
    child: Text('Increment'),
  ),
)

Redux vs Other Flutter State Management

FeatureReduxProvider/ChangeNotifierBLoCRiverpod
ComplexityHighLowMediumMedium
BoilerplateVery highLowMediumLow
Single store✅ Yes❌ Multiple❌ Multiple❌ Multiple
Time-travel debug✅ Yes❌ No❌ No❌ No
Learning curveSteepEasyModerateModerate
Best forLarge apps needing full auditabilitySimple-medium appsComplex asyncScalable modern apps

When to Use Redux in Flutter

Use ReduxDon't Use Redux
Large team needing strict patternsSmall/medium apps
Audit trail of all state changes neededMost Flutter apps
Coming from React/Redux backgroundTeams new to state management

Honest Assessment: Redux is powerful but brings significant boilerplate. Most Flutter teams prefer BLoC or Riverpod which offer similar architectural benefits with less ceremony.