Skip to main content

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:

Bash
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:

Bash
rm test/widget_test.dart

Flutter 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

Bash
grep -E '^  (flutter_riverpod|material_ui):' pubspec.yaml

Two 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.

Bash
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(),
);
DART

A 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

Bash
flutter analyze lib/practitioner.dart

The 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:

Dart
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:

Bash
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,
);
DART

Two 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

Bash
flutter analyze lib/basket.dart

You 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.

Bash
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,
);
DART

autoDispose 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:

Dart
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

Bash
flutter analyze lib/practitioners.dart

You 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:

Bash
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')),
    );
  }
}
DART

Read 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

Bash
flutter analyze

The whole project reports No issues found!. To see the app, start it on an emulator, a phone or Chrome:

Bash
flutter run

A 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:

Bash
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;
  }
}
DART

The basket is synchronous, so its test reads the notifier, calls methods and checks the state:

Bash
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);
  });
}
DART

The 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.

Bash
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();
  });
}
DART

The 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

Bash
flutter test test/basket_test.dart test/practitioners_test.dart

The 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:

Bash
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);
  });
}
DART

pumpAndSettle 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

Bash
flutter test
flutter analyze

flutter 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:

Bash
cd ~
rm -rf ~/riverpod-demo

Check it worked

Bash
test ! -d ~/riverpod-demo && echo "riverpod-demo removed"

The terminal prints riverpod-demo removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.