Sub topic 8
Keeping family arguments equal and stable
This chapter assumes you can write a @riverpod function with parameters, as covered in the previous chapter on families. It also assumes you know ConsumerWidget and ref.watch, and you know how Dart's == and hashCode work. The goal is to understand how Riverpod decides that two family calls mean the same thing. You will also learn to write arguments that keep that decision stable.
How a family finds its state
A family is a lookup table. When you write ref.watch(userProvider(42)), Riverpod builds a provider object that holds the argument 42. It then looks for an existing provider in the container that is equal to it. If one exists, you get its cached state. If none exists, Riverpod creates a new instance and runs your function.
The generated provider class overrides == and hashCode so that two providers are equal when they have the same type and equal arguments. Everything depends on the == of your argument types, not on Riverpod itself.
- Equal arguments share one state, one in-flight
Future, and one set of listeners. - Unequal arguments each get their own state, even when they look the same to a human.
With int or String this works as you expect. The trouble starts when the argument is an object you wrote yourself.
What goes wrong with identity equality
A Dart class that does not override == compares by identity. Two objects built from the same values are different objects. Consider a filter class like this:
class BadFilter {
BadFilter({required this.category});
final String category;
}If a widget calls ref.watch(productsProvider(BadFilter(category: 'books'))) inside build, every rebuild creates a new BadFilter. Riverpod sees a new argument and a new provider instance each time. The result is usually an infinite loop:
- The widget builds and watches a new provider instance, which starts loading.
- The
Futurecompletes and the instance notifies the widget. - The widget rebuilds and creates another new
BadFilter. - The new instance starts loading, so the cycle repeats.
The symptoms are a spinner that never settles, repeated network calls for the same data, and in the worst case a request storm against your server.
Writing a custom argument type correctly
Give the class final fields, a const constructor when possible, and an == and hashCode that use the same fields. This file contains a complete example. Run dart run build_runner build to produce product_providers.g.dart.
import 'package:flutter/foundation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'product_providers.g.dart';
class Product {
const Product({required this.name, required this.category, required this.price});
final String name;
final String category;
final double price;
}
class ProductRepository {
Future<List<Product>> search({required String category, double? maxPrice}) async {
const all = [
Product(name: 'Dart Guide', category: 'books', price: 25),
Product(name: 'Flutter Cookbook', category: 'books', price: 18),
Product(name: 'Desk Lamp', category: 'home', price: 30),
];
return all
.where((p) => p.category == category)
.where((p) => maxPrice == null || p.price <= maxPrice)
.toList();
}
}
@riverpod
ProductRepository productRepository(Ref ref) => ProductRepository();
@immutable
class ProductFilter {
const ProductFilter({required this.category, this.maxPrice});
final String category;
final double? maxPrice;
@override
bool operator ==(Object other) =>
other is ProductFilter &&
other.category == category &&
other.maxPrice == maxPrice;
@override
int get hashCode => Object.hash(category, maxPrice);
}
@riverpod
Future<List<Product>> products(Ref ref, ProductFilter filter) async {
final repository = ref.watch(productRepositoryProvider);
return repository.search(category: filter.category, maxPrice: filter.maxPrice);
}Three rules keep this correct:
- Compare every field that affects the result. If
maxPricewere left out of==, a filter capped at 20 would return the cached result of a filter with no cap. - Hash the same fields you compare.
Object.hashcombines several values, andObject.hashAllhandles an iterable. Equal objects must have equal hash codes, and thehash_and_equalslint inpackage:lintswarns when you override one without the other. - Mark the class
@immutableand keep every fieldfinal.
If writing this by hand is tedious, packages such as freezed and equatable generate the same == and hashCode. The result is the same, so use whichever your project already has.
Which argument types are safe
| Argument type | Stable? | Notes |
|---|---|---|
| `int`, `String`, `bool`, enums | Yes | Value equality is built in. |
| `double` | Mostly | Equal values match, but `NaN` never equals itself, and computed values such as `0.1 + 0.2` can differ slightly. |
| `const` object | Yes | Identical constant expressions are canonicalized to one instance, even without `==`. |
| Dart 3 record of stable values | Yes | Records compare field by field. Check that your generator version accepts record parameters. |
| Class with `==` and `hashCode` | Yes | Provided all compared fields are stable too. |
| Class without `==` | No | Compares by identity, so each construction is a new instance. |
| `List`, `Set`, `Map` | No | Collections compare by identity, even when the contents are the same. |
| Objects such as `BuildContext` or a `Widget` | Avoid | They carry identity and lifecycle that does not belong in a cache key. |
The const case deserves care. const BadFilter(category: 'books') written twice is the same object. A filter built from user input at runtime is never constant, so it needs real ==.
Collections as arguments
[1, 2, 3] == [1, 2, 3] is false in Dart. A list parameter, such as Future<List<Product>> productsByIds(Ref ref, List<int> ids), creates a new instance on every call that passes a fresh list literal. There are three common fixes.
- Pass a single value that identifies the set, such as a sorted, comma-joined
Stringor a single parent ID. The provider can split or look up the details itself. - Pass a wrapper class with value equality, like the one below.
- Use an immutable collection from a package such as
fast_immutable_collections, which defines==by content.
import 'package:flutter/foundation.dart';
@immutable
class IdSet {
IdSet(Iterable<int> ids) : ids = List.unmodifiable(ids.toList()..sort());
final List<int> ids;
@override
bool operator ==(Object other) =>
other is IdSet && listEquals(other.ids, ids);
@override
int get hashCode => Object.hashAll(ids);
}The constructor copies and sorts the input. IdSet([3, 1]) and IdSet([1, 3]) are then equal, and the caller cannot change the contents afterward. Sorting is a design choice. Skip it if order matters to your result.
Mutable arguments
Equality is only reliable while the object stays the same. Riverpod stores each provider in a hash-based map. If an argument's fields change after the provider is created, its hashCode changes with them. The container can no longer find the entry it stored, and you get duplicate instances or leaked state.
Avoid this by never mutating an object once you have passed it to a family. When the user changes a filter, create a new filter object. A copyWith method makes this easy. The new object is a different argument, so it gets its own state:
final next = ProductFilter(category: filter.category, maxPrice: 20);Verify equality with a test
You do not need to run the app to check an argument type. Generated providers compare equal when their arguments are equal, so a unit test can assert it directly. This test also counts repository calls through a fake.
import 'package:flutter_test/flutter_test.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'product_providers.dart';
class CountingRepository extends ProductRepository {
int calls = 0;
@override
Future<List<Product>> search({required String category, double? maxPrice}) {
calls++;
return super.search(category: category, maxPrice: maxPrice);
}
}
void main() {
test('equal filters are the same provider', () {
final a = ProductFilter(category: 'books', maxPrice: 20);
final b = ProductFilter(category: 'books', maxPrice: 20);
expect(identical(a, b), isFalse);
expect(a, equals(b));
expect(productsProvider(a), equals(productsProvider(b)));
});
test('equal filters share one fetch', () async {
final repository = CountingRepository();
final container = ProviderContainer(
overrides: [productRepositoryProvider.overrideWith((ref) => repository)],
);
addTearDown(container.dispose);
final a = ProductFilter(category: 'books');
final b = ProductFilter(category: 'books');
final subscription = container.listen(productsProvider(a), (_, __) {});
addTearDown(subscription.close);
await container.read(productsProvider(a).future);
await container.read(productsProvider(b).future);
expect(repository.calls, 1);
});
}The container.listen call keeps the auto-dispose provider alive for the duration of the test. Without it, the state could be disposed between the two reads and the second read would fetch again. If you remove == from ProductFilter, both tests fail, and that is the signal you want.
Argument stability and provider lifetime
Unstable arguments hurt more when combined with keepAlive: true. An auto-dispose provider at least discards each orphaned instance once nothing listens to it. A kept-alive family never discards anything, so every unequal argument adds an entry that stays until the container is disposed. That is a memory leak that grows with every rebuild.
A related case is arguments that are correct but change constantly, such as a search box that passes the raw text on each keystroke. Each distinct string gets its own instance and its own request. Debounce the text in the widget layer, or hold the query in a Notifier and pass only the settled value to the family.
A checklist for each family parameter
- Is the parameter a primitive, an enum, a record of those, or a class with value equality over final fields?
- If it is a collection, did you wrap it or replace it with a single identifying value?
- Does the argument come from state or from the user instead of being invented per build?
- Does a unit test assert that two equal arguments give equal providers?
Exercise
A teammate writes ref.watch(productsProvider(ProductFilter(category: 'books'))) in a build method. ProductFilter has final fields but no == or hashCode. The screen fetches data again and again. Explain why, and name two ways to fix it.
Show answer
Without ==, ProductFilter compares by identity, so each build creates an unequal argument and therefore a new provider instance. Each new instance loads, notifies the widget, and triggers another build, which starts the loop. Fix it by overriding == and hashCode over category and every other relevant field. Alternatively, make the filter a const object where the value is known at compile time, or replace it with a primitive such as the category String.
Exercise
A provider is declared as Future<int> total(Ref ref, List<int> ids), and callers pass [1, 2, 3] literals. Why is this unstable, and how would you change it so that [3, 1, 2] and [1, 2, 3] share one state?
Show answer
List literals compare by identity, so each call creates a new, unequal argument and a new provider instance. Wrap the ids in an immutable class such as IdSet that copies and sorts the input and defines == with listEquals and hashCode with Object.hashAll. Then both orderings produce equal arguments and share one cached state.