State management: Provider, Riverpod, Bloc

Learn Flutter state management with Provider, Riverpod and Bloc: how each works, how they compare to Android ViewModel and StateFlow, and when to pick one. About 28 minutes.

Why it matters

  • On Android you reach for ViewModel + StateFlow. Flutter has no single built-in equivalent, so teams choose a package. Provider, Riverpod and Bloc solve the same problem (keep state outside widgets and share it down the tree) with different trade-offs, and Flutter interviews expect you to compare them and justify a choice.
  • Where you subscribe decides what rebuilds. A context.watch at the top of a screen rebuilds the whole screen on every change, the Flutter version of collecting a StateFlow at the root composable instead of in the leaf that uses it.
  • Riverpod lets providers depend on other providers without a BuildContext and can be tested with a ProviderContainer. Bloc gives every change a named event and a hook to log each transition. Provider is the simplest and is built on Flutter's own InheritedWidget. Knowing which constraint matters for your team is a senior-level decision.
  • Mixing solutions in one codebase (for example Provider at the root and Bloc in a feature) is common in older apps. Interviewers ask you to defend one strategy or explain where the boundary is.

The simple explanation

  • What is state management in Flutter? Deciding where state lives outside individual widgets, how widgets read it, and what rebuilds when it changes. setState covers state local to one widget; the packages cover everything else.
  • Provider is dependency injection through the widget tree, like a CompositionLocal that also notifies readers. You need a BuildContext below the provider to read it.
  • Riverpod declares providers as global final values, but their state lives in a ProviderScope (a ProviderContainer), not in globals. Providers can watch other providers, which makes it feel like a ViewModel plus a small DI graph.
  • Bloc is close to an MVI ViewModel: the UI sends typed events with add, handlers emit new states, and widgets read the current state and its Stream, much like a StateFlow. Cubit drops the events and exposes methods instead.

setState marks one State object dirty and rebuilds that widget. For state that must outlive a widget or be shared across widgets, you need a container that lives higher up and notifies the widgets that read it.

Provider (package provider) is built on InheritedWidget. ChangeNotifierProvider creates a ChangeNotifier and disposes it when the provider leaves the tree. context.watch<T>() subscribes the calling widget, context.read<T>() gets the object without subscribing (use it in callbacks), and context.select or Consumer narrow what rebuilds.

Riverpod (package flutter_riverpod) wraps the app in ProviderScope. Widgets extend ConsumerWidget and get a WidgetRef; providers get a Ref. Use ref.watch in build to subscribe and ref.read in callbacks. The current API centres on Notifier/NotifierProvider and AsyncNotifier/AsyncNotifierProvider, optionally generated with riverpod_generator. StateNotifierProvider, StateProvider and ChangeNotifierProvider are legacy: Riverpod 3 moved them to a separate legacy.dart import.

Bloc (packages bloc and flutter_bloc) registers handlers with on<Event>((event, emit) { ... }) in the constructor. A Cubit calls emit from plain methods. BlocProvider creates a bloc for a subtree and closes it when removed; BlocBuilder rebuilds on new states, BlocListener runs side effects such as navigation or snackbars, and BlocSelector rebuilds on part of the state.

ProviderRiverpodBloc
Read in widgetscontext.watch / context.readref.watch / ref.readBlocBuilder, context.watch / context.read
Lookup needs BuildContext?YesNo, providers read each other with RefYes, via BlocProvider
Test logic without widgetsTest the ChangeNotifier directlyProviderContainer with overridesInstantiate the bloc, use bloc_test
Record of every changeNoObservers can log updatesEvents plus onTransition and BlocObserver
BoilerplateLowLow to mediumMedium to high (events and states)

All three keep state alive as long as the provider sits above the widgets that use it. None of them is best for every app; the choice depends on team familiarity, how much the logic needs testing in isolation, and whether an explicit event trail is worth the extra code.

Notes

  • context.watch<T>() subscribes the calling widget; context.read<T>() does not. Calling watch near the top of a screen rebuilds the whole screen on every change, so move it into the widget that needs the data, or use Consumer or context.select.
  • In Riverpod, ref.read inside build does not subscribe, so the widget will not rebuild when that provider changes. Use ref.watch in build and ref.read in event handlers such as onPressed.
  • Create a ChangeNotifier in ChangeNotifierProvider(create: ...), never inside build(). A notifier created in build is replaced on every rebuild, loses its state, and is never disposed.
  • Riverpod 3 and Bloc both skip updates when the new state is == to the current one. Emit a new immutable state object; mutating a list in place and emitting the same instance does not rebuild anything.
  • Riverpod's AsyncNotifier exposes an AsyncValue (loading, data or error), so widgets handle all three states with when or a switch. After an await in a notifier, check ref.mounted before setting state.
  • BlocProvider(create: ...) closes the bloc when it leaves the tree; BlocProvider.value does not, because it did not create it. Calling emit on a closed bloc throws a StateError.
  • Reading a bloc or provider that is not above the current BuildContext throws a "provider not found" error. Dialogs and new routes are usually outside the subtree of a screen-level provider, so pass it with BlocProvider.value or move the provider higher.
  • For streams, Riverpod's StreamProvider cancels its subscription when the provider is disposed. In a bloc, prefer emit.forEach or emit.onEach inside a handler; a subscription you create by hand must be cancelled in close().
  • Model Bloc events and states as Dart 3 sealed classes. Separate on<Subtype> handlers are not checked for exhaustiveness, but a single on<Event> handler that switches over the sealed event is.
  • Rough Android mapping: ValueNotifier is like MutableStateFlow, a ChangeNotifier is like a small observable ViewModel, Provider is like CompositionLocal DI, and a Bloc is like an MVI ViewModel with a StateFlow of states. The ideas transfer; the API names do not.

Code example

A Riverpod AsyncNotifier that loads a user name through a repository provider. The widget subscribes with ref.watch and handles loading, data and error. The same feature in Provider would be a ChangeNotifier read with context.watch; in Bloc it would be a Cubit that emits loading, loaded and error states.

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
 
class UserRepository {
  Future<String> fetchName() async {
    await Future<void>.delayed(const Duration(milliseconds: 500));
    return 'Ada Lovelace'; // replace with a real HTTP call
  }
}
 
// DI: other providers depend on this, and tests can override it.
final userRepositoryProvider = Provider<UserRepository>((ref) => UserRepository());
 
// Like a ViewModel that exposes loading/data/error state.
class UserNotifier extends AsyncNotifier<String> {
  @override
  Future<String> build() => ref.watch(userRepositoryProvider).fetchName();
 
  Future<void> refresh() async {
    state = const AsyncLoading();
    final result = await AsyncValue.guard(
      () => ref.read(userRepositoryProvider).fetchName(),
    );
    if (!ref.mounted) return; // provider disposed during the await
    state = result;
  }
}
 
final userProvider = AsyncNotifierProvider<UserNotifier, String>(UserNotifier.new);
 
class UserScreen extends ConsumerWidget {
  const UserScreen({super.key});
 
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userProvider); // subscribes: rebuilds on change
    return Center(
      child: user.when(
        data: (name) => TextButton(
          onPressed: () => ref.read(userProvider.notifier).refresh(),
          child: Text('Hello, $name'),
        ),
        loading: () => const CircularProgressIndicator(),
        error: (error, _) => Text('Error: $error'),
      ),
    );
  }
}
 
void main() {
  runApp(const ProviderScope(child: MaterialApp(home: UserScreen())));
}
  • ProviderScope at the root holds the state of every provider. The final provider declarations are only keys and recipes.
  • build() in the notifier is the initial load, like loading in a ViewModel's init. Because it uses ref.watch(userRepositoryProvider), the notifier rebuilds if the repository is replaced, for example by a test override.
  • ref.watch(userProvider) in the widget subscribes to changes; ref.read(userProvider.notifier) in onPressed gets the notifier once to call a method, without subscribing.
  • AsyncValue.guard turns a thrown error into an AsyncError instead of an uncaught exception, and user.when makes the widget handle loading, data and error.

Run the idea in plain Kotlin

// A Bloc-style container: typed events in, new states out,
// equal states skipped, every transition observable.

sealed interface CounterEvent
object Increment : CounterEvent
object Reset : CounterEvent

data class CounterState(val count: Int)

class CounterBloc(initial: CounterState) {
  var state: CounterState = initial
      private set
  private val listeners = mutableListOf<(CounterState) -> Unit>()

  fun listen(listener: (CounterState) -> Unit) { listeners.add(listener) }

  fun add(event: CounterEvent) {
      val next = when (event) {
          Increment -> state.copy(count = state.count + 1)
          Reset -> CounterState(0)
      }
      if (next == state) {
          println("skip " + event::class.simpleName + ": state unchanged")
          return
      }
      println("transition " + event::class.simpleName + ": " + state.count + " -> " + next.count)
      state = next
      listeners.forEach { it(next) }
  }
}

fun main() {
  val bloc = CounterBloc(CounterState(0))
  bloc.listen { println("  rebuild with count " + it.count) }
  bloc.add(Increment)
  bloc.add(Increment)
  bloc.add(Reset)
  bloc.add(Reset)
  println("final state: " + bloc.state.count)
}

Expected output:

transition Increment: 0 -> 1
  rebuild with count 1
transition Increment: 1 -> 2
  rebuild with count 2
transition Reset: 2 -> 0
  rebuild with count 0
skip Reset: state unchanged
final state: 0
  • The when over a sealed event type is exhaustive, like a single Bloc on<CounterEvent> handler that switches over a sealed event class.
  • The second Reset produces a state equal to the current one, so listeners are not called. Bloc and Riverpod 3 filter updates the same way with ==.
  • The transition lines play the role of Bloc's onTransition or a BlocObserver: every change has a named cause.

In production

Full-screen rebuild on every keystroke
  • A search screen called context.watch<SearchModel>() in the build method that returned the Scaffold.
  • Every character typed rebuilt the whole screen, including the AppBar, filters and bottom navigation.
  • On lower-end Android devices the frame times in profile mode went over budget and typing felt laggy.
  • The team had ported the screen from a Kotlin ViewModel + StateFlow and treated context.watch like a collectAsStateWithLifecycle call in the leaf composable.
The fix
  • Moved the subscription into a Consumer<SearchModel> that wraps only the results list.
  • Used context.select<SearchModel, String>((c) => c.query) in the one widget that shows the query.
  • Confirmed with Track widget builds in the DevTools Performance view that only the list rebuilt on each keystroke.
  • Added a review rule: subscribe at the narrowest widget that needs the data.
Stale cart total after a Riverpod migration
  • During a migration from Provider to Riverpod, context.watch calls were replaced with ref.read inside build.
  • After an item was added, the cart total kept showing the old value, because ref.read does not subscribe.
  • The bug looked intermittent: the first build read the correct value, and only later updates were missed.
The fix
  • Replaced ref.read with ref.watch everywhere inside build.
  • Kept ref.read for event handlers only, such as onPressed: () => ref.read(cartProvider.notifier).add(item).
  • Wrote a widget test that adds an item through the notifier, pumps a frame and expects the new total, so the regression fails in CI.

Common mistakes

  • Calling context.watch at the top of a screen. The whole screen rebuilds on every change. Subscribe in the widget that needs the value, or use Consumer, context.select or BlocSelector.
  • Creating a ChangeNotifier or Bloc inside build(). A new instance is made on every rebuild, the state resets, and the old one is never disposed. Create it in a provider's create callback.
  • Using ref.read inside build for reactive data. It returns the current value without subscribing, so the UI goes stale. Use ref.watch in build, ref.read in callbacks.
  • Mutating state in place and emitting it again. Riverpod 3 and Bloc compare states with ==, and the same instance is always equal to itself, so nothing rebuilds. Emit a new immutable object ([...state, item], copyWith).
  • Using BlocProvider.value to create a bloc. .value never closes the bloc, so it leaks. Use BlocProvider(create: ...) to create, and .value only to pass an existing bloc to a new route or dialog.
  • Using setState for state that several widgets share. setState rebuilds only that widget's subtree, so siblings and parents never see the change. Lift the state into a provider, notifier or bloc.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Explain the difference between Provider, Riverpod and Bloc. When would you pick each?”

“How does Provider work under the hood? What is the role of InheritedWidget?”

“What is the difference between watch and read, in Provider and in Riverpod?”

“How would you unit-test logic that uses Riverpod or Bloc without pumping a widget?”

Quiz

What happens if you call context.watch in the build method that returns a screen's Scaffold?

In Riverpod, what is the difference between ref.watch and ref.read inside a widget's build method?

Which statement about Bloc is correct?

A Cubit that has already emitted states holds a List in its state. A method adds an item to that list in place and calls emit(state). What happens?

0 of 4 answered

Mini task

15-minute exercise: Compare three state containers

  1. Create a Flutter project (flutter create statetest) and add the packages with flutter pub add provider flutter_riverpod flutter_bloc.

  2. Create an immutable CounterState with an int value and a const constructor.

  3. Provider path: Write CounterNotifier extends ChangeNotifier with an increment() that calls notifyListeners(). Provide it with ChangeNotifierProvider(create: (_) => CounterNotifier()) and show the value in a child widget with context.watch<CounterNotifier>().

  4. Riverpod path: Write CounterNotifier extends Notifier<CounterState> with build() returning const CounterState(0) and an increment() that sets state = CounterState(state.value + 1). Expose it with NotifierProvider<CounterNotifier, CounterState>(CounterNotifier.new), wrap the app in ProviderScope, and read it in a ConsumerWidget with ref.watch.

  5. Bloc path: Write CounterCubit extends Cubit<CounterState> with an increment() that calls emit(CounterState(state.value + 1)). Provide it with BlocProvider(create: (_) => CounterCubit()) and display it with BlocBuilder<CounterCubit, CounterState>.

  6. Put a debugPrint in the build of the screen and of the widget that shows the number. Tap in each version and check that only the number widget prints. Then move the subscription up into the screen's build and watch both print.

Done condition: Three working screens, one per solution, where a tap rebuilds only the widget showing the number. You can explain in one sentence why moving the subscription up into the screen changes that.

Next: Navigation and routing