Mobile development · Intermediate · 22 min
Manage app state in Flutter with Riverpod
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14 · flutter_riverpod 3.5.0
You will move a clinic booking basket out of setState into Riverpod 3.5 providers, load practitioners with an AsyncNotifier that shows loading, error and data, and prove it with ProviderContainer unit tests and a widget test that overrides the repository.
On this page
setState is the right tool for a lot of Flutter state. A text field's contents, whether a panel is expanded, the tab that is selected: if one widget owns the data and nothing else on the screen cares, keep it in that widget's State. The Flutter documentation calls this ephemeral state.
It stops working when several widgets need the same data. In a clinic booking app, the patient picks practitioners into a basket on one screen, the app bar shows how many are in it, and a later checkout screen needs the full list. With setState you end up lifting the list into a parent and passing it, and callbacks to change it, down through every widget in between. Loading data from a server adds more: a loading flag, an error, a retry, and the rule that nothing must be set after the screen has gone.
Riverpod moves that state out of the widget tree into providers. A widget asks for the state it needs and rebuilds when it changes; tests replace any provider with a fake. In this tutorial you build a small booking screen with flutter_riverpod 3.5: a basket held in a Notifier, a practitioner list loaded by an AsyncNotifier, and a screen that shows loading, error and data states. You then test the providers without any widgets, and test the screen with a fake repository.
Step 1 · Create the project and add flutter_riverpod
Make a demo folder, create an app in it and add the package. The caret range allows any 3.x release from 3.5.0 upwards, so a future 4.0 with breaking changes will not arrive by surprise:
mkdir -p ~/riverpod-demo
cd ~/riverpod-demo
flutter create clinic_basket
cd clinic_basket
flutter pub add "flutter_riverpod:^3.5.0"flutter create writes a counter app and a test for it. You replace the app, so delete the starter test now; it would fail once the counter has gone:
rm test/widget_test.dartFlutter 3.50 moved the Material widgets into their own package, material_ui, and flutter create already lists it in pubspec.yaml. The Dart files in this tutorial import package:material_ui/material_ui.dart. The older package:flutter/material.dart still works but is deprecated, so flutter analyze would report it.
Check it worked
grep -E '^ (flutter_riverpod|material_ui):' pubspec.yamlTwo lines appear under dependencies: flutter_riverpod: ^3.5.0 and material_ui with its version, such as material_ui: ^1.1.0. flutter pub add also downloaded the package, so pubspec.lock now lists flutter_riverpod and riverpod at 3.5.0 or a later 3.x.
Step 2 · Put the data source behind a provider
Start with the thing the screen loads: a list of practitioners. The screen should not know where the list comes from, so describe the source as an interface, give it a demo implementation that waits like a slow network would, and expose it through a plain Provider. That provider is the seam your tests will replace.
cat > lib/practitioner.dart <<'DART'
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Practitioner {
const Practitioner({
required this.id,
required this.name,
required this.specialty,
});
final String id;
final String name;
final String specialty;
}
abstract interface class PractitionerRepository {
Future<List<Practitioner>> fetchAll();
}
/// Stands in for an HTTP client. Swap in a real one without touching the UI.
class DemoPractitionerRepository implements PractitionerRepository {
const DemoPractitionerRepository();
@override
Future<List<Practitioner>> fetchAll() async {
await Future<void>.delayed(const Duration(milliseconds: 600));
return const [
Practitioner(id: 'amina', name: 'Dr Amina Bello', specialty: 'General practice'),
Practitioner(id: 'kofi', name: 'Dr Kofi Mensah', specialty: 'Paediatrics'),
Practitioner(id: 'wanjiru', name: 'Wanjiru Kamau', specialty: 'Physiotherapy'),
];
}
}
final practitionerRepositoryProvider = Provider<PractitionerRepository>(
(ref) => const DemoPractitionerRepository(),
);
DARTA provider is a global, immutable description of how to make a value. Declaring it at the top level is safe because it holds no state itself: the state lives in a ProviderContainer, and every app or test gets its own. That is why two tests never see each other's data.
Check it worked
flutter analyze lib/practitioner.dartThe analyser ends with No issues found!.
Step 3 · Move the basket into a Notifier
Here is how the basket would look with setState, inside the screen's State class:
class _PractitionersScreenState extends State<PractitionersScreen> {
final List<Practitioner> _basket = [];
void _add(Practitioner practitioner) {
setState(() => _basket.add(practitioner));
}
}That is fine until the app bar badge, a checkout screen and a "clear basket" action on another screen all need _basket. Move it into a Notifier. The notifier's build method returns the starting state, its methods are the only way to change it, and assigning to state tells every listener to update:
cat > lib/basket.dart <<'DART'
import 'package:clinic_basket/practitioner.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class BasketNotifier extends Notifier<List<Practitioner>> {
@override
List<Practitioner> build() => const [];
void add(Practitioner practitioner) {
if (state.any((p) => p.id == practitioner.id)) return;
state = [...state, practitioner];
}
void remove(String id) {
state = [for (final p in state) if (p.id != id) p];
}
void clear() => state = const [];
}
final basketProvider = NotifierProvider<BasketNotifier, List<Practitioner>>(
BasketNotifier.new,
);
/// Derived state: rebuilds only when the basket changes.
final basketCountProvider = Provider<int>(
(ref) => ref.watch(basketProvider).length,
);
DARTTwo details matter. Each change builds a new list instead of calling state.add, because listeners are told about a change when state is assigned; mutating the old list in place would update nothing on screen. And basketCountProvider watches basketProvider, so the count is always in step with the basket and a widget that shows only the count can depend on that one number.
The basket is not autoDispose: it should survive while the patient moves between screens. If the patient opens a practitioner's profile and comes back, the basket is still there, untouched, instead of being rebuilt empty.
Check it worked
flutter analyze lib/basket.dartYou see No issues found!.
Step 4 · Load practitioners with an AsyncNotifier
Loading is asynchronous, so use an AsyncNotifier. Its build returns a Future, and Riverpod wraps the result in an AsyncValue: AsyncLoading while it waits, then AsyncData with the list or AsyncError with the exception. You never write a loading flag yourself.
cat > lib/practitioners.dart <<'DART'
import 'package:clinic_basket/practitioner.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class PractitionersNotifier extends AsyncNotifier<List<Practitioner>> {
@override
Future<List<Practitioner>> build() {
return ref.watch(practitionerRepositoryProvider).fetchAll();
}
/// Called from the error state's "Try again" button.
Future<void> reload() async {
state = const AsyncLoading();
final result = await AsyncValue.guard(
() => ref.read(practitionerRepositoryProvider).fetchAll(),
);
if (!ref.mounted) return;
state = result;
}
}
final practitionersProvider =
AsyncNotifierProvider.autoDispose<PractitionersNotifier, List<Practitioner>>(
PractitionersNotifier.new,
);
DARTautoDispose frees the list as soon as no widget is watching it, for example when the patient leaves the booking screen, and the next visit fetches it fresh. Because of that, the notifier can be disposed while reload is waiting. ref.mounted is false after disposal, and the check stops reload from writing state into a provider that no longer exists.
Inside build, the notifier uses ref.watch on the repository, so a different repository (a test fake, or a new one after the user signs in) rebuilds the list. Inside reload, a method that runs once when called, it uses ref.read, which takes the current value without subscribing. That split is the general rule: watch in build, read in callbacks and methods.
Riverpod 3 also retries a provider that fails with an exception, by default up to 10 times with a wait that starts at 200 ms and doubles up to 6.4 seconds. That suits patchy mobile networks, but every retry is a request on the patient's data bundle. If your API is expensive to call, pass your own retry function to ProviderScope; the tests later in this tutorial turn it off.
The code generation option
Riverpod has an optional code generator. With riverpod_annotation and riverpod_generator added and dart run build_runner watch running, you annotate a class or function and the generator writes the provider declaration into a .g.dart part file:
import 'package:clinic_basket/practitioner.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'basket.g.dart';
@riverpod
class Basket extends _$Basket {
@override
List<Practitioner> build() => const [];
}That produces a basketProvider for you, auto-disposing by default, with @Riverpod(keepAlive: true) to keep it alive. It removes the long generic types and makes family parameters easier. This tutorial writes providers by hand because every line you need is then visible in your own files, there is no build step to forget, and the generated code is easier to read once you know what it replaces. Moving to the generator later changes the declarations, not the widgets or the tests.
Check it worked
flutter analyze lib/practitioners.dartYou see No issues found!.
Step 5 · Read the state in widgets
Replace lib/main.dart. ProviderScope at the root holds the state of every provider. ConsumerWidget gives build a WidgetRef, which is how a widget watches providers:
cat > lib/main.dart <<'DART'
import 'package:clinic_basket/basket.dart';
import 'package:clinic_basket/practitioners.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const ProviderScope(child: ClinicApp()));
}
class ClinicApp extends StatelessWidget {
const ClinicApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Clinic basket',
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)),
home: const PractitionersScreen(),
);
}
}
class PractitionersScreen extends ConsumerWidget {
const PractitionersScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final practitioners = ref.watch(practitionersProvider);
final basket = ref.watch(basketProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Book a visit'),
actions: const [BasketBadge()],
),
body: practitioners.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Could not load practitioners.'),
const SizedBox(height: 12),
FilledButton(
onPressed: () => ref.read(practitionersProvider.notifier).reload(),
child: const Text('Try again'),
),
],
),
),
data: (list) => ListView(
children: [
for (final p in list)
ListTile(
title: Text(p.name),
subtitle: Text(p.specialty),
trailing: basket.any((b) => b.id == p.id)
? TextButton(
key: Key('remove-${p.id}'),
onPressed: () => ref.read(basketProvider.notifier).remove(p.id),
child: const Text('Remove'),
)
: FilledButton(
key: Key('add-${p.id}'),
onPressed: () => ref.read(basketProvider.notifier).add(p),
child: const Text('Add'),
),
),
],
),
),
);
}
}
class BasketBadge extends ConsumerWidget {
const BasketBadge({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(basketCountProvider);
return Padding(
padding: const EdgeInsets.only(right: 16),
child: Center(child: Text('Basket: $count')),
);
}
}
DARTRead it against the rule from the last step. build calls ref.watch, so the screen rebuilds when the list or the basket changes. The button callbacks call ref.read(...notifier), because a tap needs the notifier once and must not subscribe to anything. AsyncValue.when makes you handle all three states, so the screen can never show an empty list while it is still loading.
BasketBadge is its own ConsumerWidget that watches only the count. No widget passes the basket to it; it asks for it. A checkout screen added later would do the same.
The error message is short and the retry is a button the patient taps. On a slow or metered connection that is better than retrying forever in the background, and a short message is easier to translate when you add Swahili, Hausa or French strings later.
Check it worked
flutter analyzeThe whole project reports No issues found!. To see the app, start it on an emulator, a phone or Chrome:
flutter runA spinner shows for about half a second, then three practitioners. Tap Add next to Dr Amina Bello: the button becomes Remove and the app bar reads Basket: 1. Press q in the terminal to stop the app.
Step 6 · Test the providers with ProviderContainer
Providers can be tested without building a single widget. ProviderContainer.test() creates a fresh container and disposes it when the test ends. First, a fake repository the tests control. It counts calls and can be told to fail. It lives in test/ but does not end in _test.dart, so flutter test does not run it as a test file:
cat > test/fakes.dart <<'DART'
import 'package:clinic_basket/practitioner.dart';
const amina = Practitioner(id: 'amina', name: 'Dr Amina Bello', specialty: 'General practice');
const kofi = Practitioner(id: 'kofi', name: 'Dr Kofi Mensah', specialty: 'Paediatrics');
class FakePractitionerRepository implements PractitionerRepository {
FakePractitionerRepository(this.practitioners);
final List<Practitioner> practitioners;
Object? error;
int calls = 0;
@override
Future<List<Practitioner>> fetchAll() async {
calls++;
final failure = error;
if (failure != null) throw failure;
return practitioners;
}
}
DARTThe basket is synchronous, so its test reads the notifier, calls methods and checks the state:
cat > test/basket_test.dart <<'DART'
import 'package:clinic_basket/basket.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fakes.dart';
void main() {
test('adds each practitioner once and keeps the count in step', () {
final container = ProviderContainer.test();
final basket = container.read(basketProvider.notifier);
basket.add(amina);
basket.add(amina);
basket.add(kofi);
expect(container.read(basketProvider).map((p) => p.id).toList(), ['amina', 'kofi']);
expect(container.read(basketCountProvider), 2);
basket.remove('amina');
expect(container.read(basketCountProvider), 1);
basket.clear();
expect(container.read(basketProvider), isEmpty);
});
}
DARTThe practitioner list needs three tests: it loads, it fails cleanly, and autoDispose really frees it. Each one overrides practitionerRepositoryProvider with the fake. Because the provider is autoDispose, each test keeps a listener open with container.listen while it works; without one, the provider could be disposed before its future completes.
cat > test/practitioners_test.dart <<'DART'
import 'package:clinic_basket/practitioner.dart';
import 'package:clinic_basket/practitioners.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fakes.dart';
void main() {
test('loads practitioners from the repository', () async {
final repository = FakePractitionerRepository([amina, kofi]);
final container = ProviderContainer.test(
overrides: [practitionerRepositoryProvider.overrideWithValue(repository)],
);
final subscription = container.listen(practitionersProvider, (_, _) {});
expect(container.read(practitionersProvider).isLoading, isTrue);
final list = await container.read(practitionersProvider.future);
expect(list.map((p) => p.name).toList(), ['Dr Amina Bello', 'Dr Kofi Mensah']);
subscription.close();
});
test('ends in an error state when the repository fails', () async {
final repository = FakePractitionerRepository(const [])..error = Exception('offline');
final container = ProviderContainer.test(
overrides: [practitionerRepositoryProvider.overrideWithValue(repository)],
retry: (_, _) => null,
);
final subscription = container.listen(practitionersProvider, (_, _) {});
await expectLater(container.read(practitionersProvider.future), throwsA(anything));
expect(container.read(practitionersProvider).hasError, isTrue);
expect(repository.calls, 1);
subscription.close();
});
test('autoDispose drops the list once nothing listens', () async {
final repository = FakePractitionerRepository([amina]);
final container = ProviderContainer.test(
overrides: [practitionerRepositoryProvider.overrideWithValue(repository)],
);
final first = container.listen(practitionersProvider, (_, _) {});
await container.read(practitionersProvider.future);
first.close();
await container.pump();
final second = container.listen(practitionersProvider, (_, _) {});
await container.read(practitionersProvider.future);
expect(repository.calls, 2);
second.close();
});
}
DARTThe error test passes retry: (_, _) => null. Without it, Riverpod would retry the failing fake in the background, repository.calls would keep climbing, and the test would depend on timing. The autoDispose test proves disposal by its effect: after the only listener closes and the container settles with pump, the next listener triggers a second fetch.
Check it worked
flutter test test/basket_test.dart test/practitioners_test.dartThe run ends with All tests passed! and reports four tests. If the autoDispose test fails with calls at 1, check that practitionersProvider uses AsyncNotifierProvider.autoDispose.
Step 7 · Test the screen with ProviderScope overrides
A widget test wraps the app in its own ProviderScope and overrides the repository, so the screen never touches the demo data or a network. The first test walks through loading, data and a tap on Add; the second fails the first load, then checks that Try again recovers:
cat > test/practitioners_screen_test.dart <<'DART'
import 'package:clinic_basket/main.dart';
import 'package:clinic_basket/practitioner.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fakes.dart';
void main() {
testWidgets('lists practitioners and fills the basket', (tester) async {
final repository = FakePractitionerRepository([amina, kofi]);
await tester.pumpWidget(
ProviderScope(
overrides: [practitionerRepositoryProvider.overrideWithValue(repository)],
child: const ClinicApp(),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Dr Amina Bello'), findsOneWidget);
expect(find.text('Basket: 0'), findsOneWidget);
await tester.tap(find.byKey(const Key('add-amina')));
await tester.pump();
expect(find.text('Basket: 1'), findsOneWidget);
expect(find.byKey(const Key('remove-amina')), findsOneWidget);
expect(find.byKey(const Key('add-kofi')), findsOneWidget);
});
testWidgets('shows an error and recovers on Try again', (tester) async {
final repository = FakePractitionerRepository([amina])..error = Exception('offline');
await tester.pumpWidget(
ProviderScope(
overrides: [practitionerRepositoryProvider.overrideWithValue(repository)],
retry: (_, _) => null,
child: const ClinicApp(),
),
);
await tester.pumpAndSettle();
expect(find.text('Could not load practitioners.'), findsOneWidget);
repository.error = null;
await tester.tap(find.text('Try again'));
await tester.pumpAndSettle();
expect(find.text('Could not load practitioners.'), findsNothing);
expect(find.text('Dr Amina Bello'), findsOneWidget);
});
}
DARTpumpAndSettle keeps drawing frames until nothing is animating, which here means the spinner has gone and the list is on screen. The tap uses the keys from main.dart because every row has a button labelled Add; a key picks out one row without depending on its position.
Check it worked
flutter test
flutter analyzeflutter test runs all three test files and ends with All tests passed! (six tests). flutter analyze still reports No issues found!, which confirms the test files are clean too.
Step 8 · Clean up
The next command deletes the demo folder and everything in it, including the tests. Your Flutter SDK is not touched:
cd ~
rm -rf ~/riverpod-demoCheck it worked
test ! -d ~/riverpod-demo && echo "riverpod-demo removed"The terminal prints riverpod-demo removed.
Next steps
- Lay out richer screens for the same app in build Flutter screens from widgets, rows, columns and lists.
- Add a checkout screen that reads the same
basketProviderwith navigate between Flutter screens with go_router. - If Flutter is not set up yet, start with install Flutter and run your first app.
Related tutorials
- How to Install Flutter 3.50 and Run Your First AppYou will install the Flutter 3.50 SDK on macOS or Linux, check your setup with flutter doctor, create an app, run it in a browser or on a device, change it with hot reload, replace the counter with your own screen, and write a widget test.
- Build Flutter screens from widgets, rows, columns and listsYou will build a clinic services screen in Flutter 3.50 from rows, columns and a lazy list, make taps update it with setState, theme it with Material 3 and prove it works at phone size with a widget test.
- Navigate between Flutter screens with go_routerYou will build a small Flutter reading-list app whose screens are reached by URL through go_router 18.1, with path parameters, bottom tabs that keep their own history, a sign-in redirect, correct Android back behaviour and deep-link configuration, all proved by widget tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials