Sub topic 2
Providers with state and methods: Notifier and AsyncNotifier
This chapter assumes you have Riverpod 2.x with riverpod_annotation, riverpod_generator, and build_runner set up, that you can read ref.watch and ref.read, and that you know Dart Future and async/await. Run dart run build_runner watch while you work so the .g.dart files stay current.
A Notifier is a provider that owns mutable state and exposes methods that change it. An AsyncNotifier does the same for state that loads asynchronously. You write a class that extends the generated _$ClassName base class. The build method returns the initial state.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
}For async state, make build return a Future:
@riverpod
class Greeting extends _$Greeting {
@override
Future<String> build() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 'Hello';
}
}Provider lifetime: auto-dispose and keepAlive
Generated providers are auto-dispose by default. When no widget or other provider listens to them, Riverpod destroys their state. Add keepAlive: true to keep the state for the life of the ProviderScope:
@Riverpod(keepAlive: true)
Future<String> settings(Ref ref) async => 'loaded';Use auto-dispose for data tied to a screen. Use keepAlive for data that should survive navigation, such as a session token.
Families: turning parameters into provider instances
Add parameters after ref and Riverpod creates a family. Each distinct argument gets its own state:
@riverpod
Future<String> greeting(Ref ref, String name) async => 'Hello, $name';
// ref.watch(greetingProvider('Ada')) and ref.watch(greetingProvider('Lin')) are separate states.Keeping family arguments equal and stable
Riverpod finds an existing instance by comparing arguments with ==. Built-in types such as int and String compare by value, so they work. A custom class compares by identity unless you override == and hashCode. Without that override, each new object creates a new instance and the cache never hits.
import 'package:flutter/foundation.dart';
@immutable
class Filter {
const Filter({required this.category});
final String category;
@override
bool operator ==(Object other) =>
other is Filter && other.category == category;
@override
int get hashCode => category.hashCode;
}Exercise
A family takes a Filter object with no == override. A widget calls ref.watch(productsProvider(Filter(category: 'books'))) on every rebuild. What happens to the state?
Show answer
Each rebuild passes a new object that compares unequal to the previous one, so Riverpod creates a new instance and fetches again. Add == and hashCode to Filter so equal filters share one instance.