Back to blog

cat blog/la-gestion-detat-en-flutter-setstate-provider-riverpod-ou-bloc.md

·Mobile·6 min read

State management in Flutter: setState, Provider, Riverpod or Bloc

Solution Architect

State management in Flutter: setState, Provider, Riverpod or BlocState management in Flutter: setState, Provider, Riverpod or Bloc
Contents
  1. setState: perfect for ephemeral state
  2. Provider: the next step
  3. Riverpod: state without BuildContext
  4. Bloc: explicit states and traceable transitions
  5. How I choose
  6. End of the series
  7. Sources

In the previous article, Clean Architecture with Flutter, the widget no longer made any network call: it displayed a state provided by the presentation layer. What remained was how to build that state. It's one of the most debated questions in the Flutter ecosystem, and the last article in this series.

Before comparing tools, a distinction the official Flutter documentation makes, which settles half the debate:

  • ephemeral state concerns a single widget: the selected tab, a checked box, the running animation. Nobody else needs it;

  • app state is shared between several screens or must outlive a widget: the logged-in user, the cart, the list of orders.

No tool should handle both the same way. I use the same example for each: the screen showing active orders, with a loading, success and error state.

setState: perfect for ephemeral state

setState is built into Flutter and needs no dependency. For state that never leaves the widget, it's the right choice, not a beginner's choice:

class _FilterChipsState extends State<FilterChips> {
  OrderFilter _selected = OrderFilter.all;

  @override
  Widget build(BuildContext context) {
    return Wrap(
      children: OrderFilter.values.map((filter) => ChoiceChip(
            label: Text(filter.label),
            selected: _selected == filter,
            onSelected: (_) => setState(() => _selected = filter),
          )).toList(),
    );
  }
}

Its limits appear as soon as state must be shared: you end up passing data and callbacks from widget to widget, and business logic lands in the UI, exactly what Clean Architecture aimed to avoid.

Provider: the next step

Provider relies on ChangeNotifier, the Observer pattern from the patterns article. State lives in a separate class, and widgets subscribe:

class OrdersNotifier extends ChangeNotifier {
  OrdersNotifier(this._getActiveOrders);

  final GetActiveOrders _getActiveOrders;

  List<Order> orders = [];
  bool isLoading = false;
  String? error;

  Future<void> load() async {
    isLoading = true;
    error = null;
    notifyListeners();
    try {
      orders = await _getActiveOrders();
    } catch (e) {
      error = 'Could not load orders';
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}
// In the widget tree
ChangeNotifierProvider(
  create: (_) => OrdersNotifier(getIt())..load(),
  child: const OrdersPage(),
);

// In the screen
final state = context.watch<OrdersNotifier>();
if (state.isLoading) return const CircularProgressIndicator();

Provider is simple and widely documented. Its weak points: three fields (orders, isLoading, error) that can contradict each other, and a dependency on BuildContext that makes accessing state outside widgets awkward.

Riverpod: state without BuildContext

Riverpod was created by Provider's author to fix its limits. Providers are declared outside the widget tree, no longer depend on BuildContext, and also serve as dependency injection. Above all, AsyncValue solves the problem of the three contradictory fields: a state is either loading, failed or loaded, never two at once.

// The repository comes from the data layer (here via get_it)
final orderRepositoryProvider = Provider<OrderRepository>(
  (ref) => getIt<OrderRepository>(),
);

final getActiveOrdersProvider = Provider(
  (ref) => GetActiveOrders(ref.watch(orderRepositoryProvider)),
);

class ActiveOrdersNotifier extends AsyncNotifier<List<Order>> {
  @override
  Future<List<Order>> build() => ref.watch(getActiveOrdersProvider)();
}

final activeOrdersProvider =
    AsyncNotifierProvider<ActiveOrdersNotifier, List<Order>>(ActiveOrdersNotifier.new);
class OrdersPage extends ConsumerWidget {
  const OrdersPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final orders = ref.watch(activeOrdersProvider);

    return orders.when(
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, _) => ErrorView(onRetry: () => ref.invalidate(activeOrdersProvider)),
      data: (list) => ListView(children: [for (final o in list) OrderTile(order: o)]),
    );
  }
}

Little code, no inconsistent state possible, and caching, refreshing (ref.invalidate) and resource disposal come built in. The downside: a real learning curve, with its own notions (ref.watch versus ref.read, provider scope).

Bloc: explicit states and traceable transitions

Bloc enforces strict separation: the UI sends actions, the Bloc class emits states. Its lighter version, Cubit, is enough in most cases. With Dart 3 sealed classes, each state is its own type, and the compiler checks no case is forgotten: that's the State pattern from the patterns article.

sealed class OrdersState {}
final class OrdersLoading extends OrdersState {}
final class OrdersLoaded extends OrdersState {
  OrdersLoaded(this.orders);
  final List<Order> orders;
}
final class OrdersError extends OrdersState {
  OrdersError(this.message);
  final String message;
}

class OrdersCubit extends Cubit<OrdersState> {
  OrdersCubit(this._getActiveOrders) : super(OrdersLoading());

  final GetActiveOrders _getActiveOrders;

  Future<void> load() async {
    emit(OrdersLoading());
    try {
      emit(OrdersLoaded(await _getActiveOrders()));
    } catch (_) {
      emit(OrdersError('Could not load orders'));
    }
  }
}
BlocProvider(
  create: (_) => OrdersCubit(getIt())..load(),
  child: BlocBuilder<OrdersCubit, OrdersState>(
    builder: (context, state) => switch (state) {
      OrdersLoading() => const Center(child: CircularProgressIndicator()),
      OrdersError(:final message) =>
        ErrorView(message: message, onRetry: context.read<OrdersCubit>().load),
      OrdersLoaded(:final orders) =>
        ListView(children: [for (final o in orders) OrderTile(order: o)]),
    },
  ),
);

More verbose than Riverpod, but very readable: every transition is explicit, testable with bloc_test, and traceable with a BlocObserver. It's the tool I use most, alone or in a team: for me, predictability matters more than brevity.

How I choose

Criterion

setState

Provider

Riverpod

Bloc (Cubit)

Ideal scope

One widget's state

Small app, simple shared state

Any size

Medium and large apps

Amount of code

Minimal

Low

Low

Higher

Inconsistent states possible

Yes

Yes (separate fields)

No (AsyncValue)

No (sealed states)

Depends on BuildContext

Yes

Yes

No

Yes, for access

Dependency injection

Separate

Separate

Built in

Separate (get_it)

Testing

Widget tests

Simple

Simple (ProviderContainer)

Very simple (bloc_test)

Learning curve

None

Low

Medium

Medium

My rules, which aren't mutually exclusive:

  1. setState for anything that stays in one widget. A form, a tab, an animation. Even in an app using Riverpod or Bloc.

  2. Bloc with Cubit by default, including when I work alone. A Cubit stays short, sealed states are checked by the compiler, and the same structure holds when the app grows or a team joins me. I switch to a full Bloc (with events) when the business has complex transitions: a payment flow, a multi-step form.

  3. Riverpod on some projects, when the app is mostly async data to load, cache and refresh. There, AsyncValue and built-in injection save a lot of code.

  4. Provider to take over an existing project that already uses it. I don't migrate a working app just to follow trends.

What matters most isn't the tool, but the rule from the previous article: state management calls the domain, it doesn't replace it. A Cubit or Notifier that makes HTTP calls itself recreates the original problem, with more files.

End of the series

This series started from a simple question: why did the same comments keep coming back in code review? The answer took five articles:

  1. What code review taught me while leading a team

  2. The design patterns I use every day

  3. SOLID principles in practice

  4. Clean Architecture with Flutter

  5. State management in Flutter (this article)

The common thread fits in one sentence: good code isn't the one applying the most rules, but the one the next person understands and changes without fear.

Sources

To train your team on this topicFlutter: mobile apps ready for production

Share:

subscribe --blog

Get new posts by email

One email per new post, nothing else. Unsubscribe in one click.

Your address is only used to send you new posts. Privacy