State management: Provider, Riverpod, Bloc
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.watchat the top of a screen rebuilds the whole screen on every change, the Flutter version of collecting aStateFlowat the root composable instead of in the leaf that uses it. - Riverpod lets providers depend on other providers without a
BuildContextand can be tested with aProviderContainer. Bloc gives every change a named event and a hook to log each transition. Provider is the simplest and is built on Flutter's ownInheritedWidget. 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.
setStatecovers state local to one widget; the packages cover everything else. - Provider is dependency injection through the widget tree, like a
CompositionLocalthat also notifies readers. You need aBuildContextbelow the provider to read it. - Riverpod declares providers as global
finalvalues, but their state lives in aProviderScope(aProviderContainer), not in globals. Providers can watch other providers, which makes it feel like aViewModelplus a small DI graph. - Bloc is close to an MVI
ViewModel: the UI sends typed events withadd, handlersemitnew states, and widgets read the currentstateand itsStream, much like aStateFlow.Cubitdrops 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.
| Provider | Riverpod | Bloc | |
|---|---|---|---|
| Read in widgets | context.watch / context.read | ref.watch / ref.read | BlocBuilder, context.watch / context.read |
Lookup needs BuildContext? | Yes | No, providers read each other with Ref | Yes, via BlocProvider |
| Test logic without widgets | Test the ChangeNotifier directly | ProviderContainer with overrides | Instantiate the bloc, use bloc_test |
| Record of every change | No | Observers can log updates | Events plus onTransition and BlocObserver |
| Boilerplate | Low | Low to medium | Medium 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. Callingwatchnear the top of a screen rebuilds the whole screen on every change, so move it into the widget that needs the data, or useConsumerorcontext.select.- In Riverpod,
ref.readinsidebuilddoes not subscribe, so the widget will not rebuild when that provider changes. Useref.watchinbuildandref.readin event handlers such asonPressed. - Create a
ChangeNotifierinChangeNotifierProvider(create: ...), never insidebuild(). A notifier created inbuildis 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
AsyncNotifierexposes anAsyncValue(loading, data or error), so widgets handle all three states withwhenor aswitch. After anawaitin a notifier, checkref.mountedbefore settingstate. BlocProvider(create: ...)closes the bloc when it leaves the tree;BlocProvider.valuedoes not, because it did not create it. Callingemiton a closed bloc throws aStateError.- Reading a bloc or provider that is not above the current
BuildContextthrows a "provider not found" error. Dialogs and new routes are usually outside the subtree of a screen-level provider, so pass it withBlocProvider.valueor move the provider higher. - For streams, Riverpod's
StreamProvidercancels its subscription when the provider is disposed. In a bloc, preferemit.forEachoremit.onEachinside a handler; a subscription you create by hand must be cancelled inclose(). - Model Bloc events and states as Dart 3 sealed classes. Separate
on<Subtype>handlers are not checked for exhaustiveness, but a singleon<Event>handler thatswitches over the sealed event is. - Rough Android mapping:
ValueNotifieris likeMutableStateFlow, aChangeNotifieris like a small observableViewModel, Provider is likeCompositionLocalDI, and a Bloc is like an MVIViewModelwith aStateFlowof 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())));
}ProviderScopeat the root holds the state of every provider. Thefinalprovider declarations are only keys and recipes.build()in the notifier is the initial load, like loading in aViewModel'sinit. Because it usesref.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)inonPressedgets the notifier once to call a method, without subscribing.AsyncValue.guardturns a thrown error into anAsyncErrorinstead of an uncaught exception, anduser.whenmakes 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
whenover a sealed event type is exhaustive, like a single Blocon<CounterEvent>handler thatswitches over a sealed event class. - The second
Resetproduces a state equal to the current one, so listeners are not called. Bloc and Riverpod 3 filter updates the same way with==. - The
transitionlines play the role of Bloc'sonTransitionor aBlocObserver: every change has a named cause.
In production
- A search screen called
context.watch<SearchModel>()in thebuildmethod that returned theScaffold. - 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+StateFlowand treatedcontext.watchlike acollectAsStateWithLifecyclecall in the leaf composable.
- 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.
- During a migration from Provider to Riverpod,
context.watchcalls were replaced withref.readinsidebuild. - After an item was added, the cart total kept showing the old value, because
ref.readdoes not subscribe. - The bug looked intermittent: the first build read the correct value, and only later updates were missed.
- Replaced
ref.readwithref.watcheverywhere insidebuild. - Kept
ref.readfor event handlers only, such asonPressed: () => 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.selectorBlocSelector. - 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
createcallback. - Using ref.read inside build for reactive data. It returns the current value without subscribing, so the UI goes stale. Use
ref.watchinbuild,ref.readin 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.
.valuenever closes the bloc, so it leaks. UseBlocProvider(create: ...)to create, and.valueonly to pass an existing bloc to a new route or dialog. - Using setState for state that several widgets share.
setStaterebuilds 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
-
Create a Flutter project (
flutter create statetest) and add the packages withflutter pub add provider flutter_riverpod flutter_bloc. -
Create an immutable
CounterStatewith anint valueand aconstconstructor. -
Provider path: Write
CounterNotifier extends ChangeNotifierwith anincrement()that callsnotifyListeners(). Provide it withChangeNotifierProvider(create: (_) => CounterNotifier())and show the value in a child widget withcontext.watch<CounterNotifier>(). -
Riverpod path: Write
CounterNotifier extends Notifier<CounterState>withbuild()returningconst CounterState(0)and anincrement()that setsstate = CounterState(state.value + 1). Expose it withNotifierProvider<CounterNotifier, CounterState>(CounterNotifier.new), wrap the app inProviderScope, and read it in aConsumerWidgetwithref.watch. -
Bloc path: Write
CounterCubit extends Cubit<CounterState>with anincrement()that callsemit(CounterState(state.value + 1)). Provide it withBlocProvider(create: (_) => CounterCubit())and display it withBlocBuilder<CounterCubit, CounterState>. -
Put a
debugPrintin thebuildof 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'sbuildand 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.