When is plain setState sufficient for state management?
setState works perfectly for state that belongs to a single widget and does not need to be shared. Adding a full state management library for local state is unnecessary overhead.
Choose the right approach and follow proven patterns for managing state
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
Choosing the right state management solution depends on your project size, team experience, and application complexity. There is no single best approach for every app. A small personal project might work perfectly with setState or GetX, while a large production app with multiple developers benefits from the structure and testability of BLoC or Riverpod. Understanding when and why to use each approach is just as important as knowing how to use them. This lesson covers practical guidelines, common patterns, and real-world decision strategies.
Consider these factors when deciding on a state management approach. For local widget state like form inputs, animations, and toggles, plain setState is sufficient and adding a state management library is unnecessary overhead. For shared state that multiple widgets need to access, use a library. For apps with heavy async operations like API calls and real-time streams, Riverpod or BLoC handle loading and error states elegantly. For large teams, BLoC enforces consistency through its strict event-state pattern. For solo developers or small teams wanting fast iteration, Riverpod or GetX reduce boilerplate.
1// PATTERN 1: Separate state classes (works with BLoC, Riverpod, GetX)2// Instead of managing raw values, define state classes34// Bad: multiple loose variables5// bool isLoading, String? error, List<User> users67// Good: sealed state class8sealed class UserState {}9class UserInitial extends UserState {}10class UserLoading extends UserState {}11class UserLoaded extends UserState {12final List<User> users;13UserLoaded(this.users);14}15class UserError extends UserState {16final String message;17UserError(this.message);18}1920// PATTERN 2: Repository pattern for data access21abstract class UserRepository {22Future<List<User>> getUsers();23Future<User> getUserById(String id);24Future<void> createUser(User user);25}2627class FirebaseUserRepository implements UserRepository {28final FirebaseFirestore _db;29FirebaseUserRepository(this._db);3031@override32Future<List<User>> getUsers() async {33final snapshot = await _db.collection('users').get();34return snapshot.docs.map((d) => User.fromJson(d.data())).toList();35}3637@override38Future<User> getUserById(String id) async {39final doc = await _db.collection('users').doc(id).get();40return User.fromJson(doc.data()!);41}4243@override44Future<void> createUser(User user) async {45await _db.collection('users').doc(user.id).set(user.toJson());46}47}
In real apps, you often need to react to state changes beyond just rebuilding the UI. BlocListener lets you perform side effects like navigation, showing snackbars, or logging when a state changes. BlocConsumer combines both BlocBuilder and BlocListener in a single widget. When your screen depends on multiple BLoCs, use MultiBlocProvider to provide them all at once.
1// BlocListener: side effects (navigation, snackbar, dialog)2BlocListener<AuthCubit, AuthState>(3listener: (context, state) {4if (state is AuthSuccess) {5Navigator.pushReplacement(6context,7MaterialPageRoute(builder: (_) => const HomePage()),8);9}10if (state is AuthError) {11ScaffoldMessenger.of(context).showSnackBar(12SnackBar(content: Text(state.message)),13);14}15},16child: const LoginForm(),17)1819// BlocConsumer: builder + listener combined20BlocConsumer<CartCubit, CartState>(21listener: (context, state) {22if (state is CartUpdated) {23ScaffoldMessenger.of(context).showSnackBar(24const SnackBar(content: Text('Cart updated')),25);26}27},28builder: (context, state) {29if (state is CartLoaded) {30return CartList(items: state.items);31}32return const CircularProgressIndicator();33},34)3536// MultiBlocProvider for screens needing multiple BLoCs37MultiBlocProvider(38providers: [39BlocProvider(create: (_) => UserCubit(userRepo)),40BlocProvider(create: (_) => CartCubit(cartRepo)),41BlocProvider(create: (_) => NotificationCubit()),42],43child: const DashboardScreen(),44)
Riverpod 2.x and 3.x introduced Notifier and AsyncNotifier as replacements for StateNotifier. These new classes are simpler to write, support code generation with the @riverpod annotation, and integrate better with the rest of the Riverpod ecosystem. AsyncNotifier automatically handles loading and error states for async operations.
1// Modern Riverpod: Notifier (replaces StateNotifier)2class TodoNotifier extends Notifier<List<Todo>> {3@override4List<Todo> build() => []; // initial state56void add(Todo todo) {7state = [...state, todo];8}910void toggle(String id) {11state = [12for (final todo in state)13if (todo.id == id) todo.copyWith(done: !todo.done) else todo14];15}16}1718final todoProvider = NotifierProvider<TodoNotifier, List<Todo>>(19TodoNotifier.new,20);2122// AsyncNotifier for async operations23class UserNotifier extends AsyncNotifier<List<User>> {24@override25Future<List<User>> build() async {26// Automatically sets loading state, then data or error27final repo = ref.watch(userRepositoryProvider);28return repo.getUsers();29}3031Future<void> addUser(User user) async {32state = const AsyncLoading();33state = await AsyncValue.guard(() async {34await ref.read(userRepositoryProvider).createUser(user);35return ref.read(userRepositoryProvider).getUsers();36});37}38}3940final userProvider = AsyncNotifierProvider<UserNotifier, List<User>>(41UserNotifier.new,42);4344// Using AsyncNotifier in UI (handles loading/error/data)45class UserListPage extends ConsumerWidget {46@override47Widget build(BuildContext context, WidgetRef ref) {48final usersAsync = ref.watch(userProvider);4950return usersAsync.when(51loading: () => const CircularProgressIndicator(),52error: (e, stack) => Text('Error: $e'),53data: (users) => ListView.builder(54itemCount: users.length,55itemBuilder: (_, i) => ListTile(title: Text(users[i].name)),56),57);58}59}
Pick one primary state management library and use it consistently throughout your app. Mixing BLoC and Riverpod in the same project creates confusion, makes testing harder, and increases the learning curve for new team members. The only exception is using plain setState for purely local widget state like animations or form field focus.
Never put API calls, data transformations, or validation logic directly in your widget build methods or onPressed callbacks. Always move business logic into a Cubit, BLoC, Notifier, or Controller class. This keeps widgets focused on UI rendering and makes your logic reusable and testable.
For team projects, state management choice should be policy, not preference:
Teams that standardize decisions early move faster with fewer regressions.
Choose the right approach and follow proven patterns for managing state. State is data that changes over time and controls what users see on the screen.
Think in architecture, reliability, and team-level maintainability.
Keep state as close as possible to where it is used, then lift it only when sharing is required.
State management is the difference between predictable apps and hard-to-debug UI behavior.
State boundaries define module boundaries, so clear ownership prevents future regressions.
As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.
setState works perfectly for state that belongs to a single widget and does not need to be shared. Adding a full state management library for local state is unnecessary overhead.
BlocListener reacts to state changes by executing side effects such as navigation, showing snackbars, or logging. It does not rebuild the UI. Use BlocBuilder for UI rebuilds.
AsyncNotifier automatically sets the state to loading when an async operation starts, then to data on success or error on failure, removing the need for manual state tracking.
Sealed state classes force you to handle every possible state (initial, loading, loaded, error) in switch statements. The compiler warns you if you miss a state, preventing bugs.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue