Sub topic 4
Reading providers with ConsumerWidget and WidgetRef
This chapter assumes you can write a Flutter StatelessWidget and StatefulWidget. It also assumes you have a ProviderScope at the root of your app and have declared a simple Provider, as in the previous chapters. Here you learn how a widget gets access to a provider, what the WidgetRef object is, and which widget type to pick for which job.
Why a plain widget cannot read a provider
A provider is declared as a global final variable, but it holds no state itself. The state lives in a provider container, which ProviderScope creates and places at the top of the widget tree. A widget needs a handle to that container to read anything.
A StatelessWidget only receives a BuildContext. Riverpod does not add a way to read providers to BuildContext. Instead, the flutter_riverpod package provides widget types that pass in a second object, the WidgetRef.
A WidgetRef is the widget's connection to the provider container. Through it you can:
- read a provider's value and subscribe to changes (
ref.watch), - read a value once without subscribing (
ref.read), - run a callback when a value changes (
ref.listen), - ask a provider to recompute (
ref.invalidate,ref.refresh).
This chapter focuses on obtaining a ref and using ref.watch to display a value. The next chapter compares watch and read in detail.
ConsumerWidget
ConsumerWidget replaces StatelessWidget when a widget needs providers. The only difference in code is the base class and the extra build parameter.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final greeting = ref.watch(greetingProvider);
return MaterialApp(
home: Scaffold(body: Center(child: Text(greeting))),
);
}
}Three details matter here:
- The widget class extends
ConsumerWidget, notStatelessWidget. buildtakes(BuildContext context, WidgetRef ref). If you copy aStatelessWidgetand forget the second parameter, the override does not compile.ref.watch(greetingProvider)subscribes this widget to the provider. When the provider's value changes, Riverpod marks this widget dirty and Flutter callsbuildagain.
A ConsumerWidget is still stateless in the Flutter sense. It has no State object, so it cannot hold local mutable fields. Application state belongs in providers, and local UI state such as a text controller belongs in a stateful widget.
Consumer: rebuilding only a small part of the tree
Sometimes only a small piece of a large widget needs a provider. Making the whole widget a ConsumerWidget would rebuild everything under it whenever the value changes. A Consumer is a widget that gives you a ref inside any existing build method, so you can narrow the part of the tree that rebuilds.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');
class Header extends StatelessWidget {
const Header({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Static title'),
Consumer(
builder: (context, ref, child) {
final greeting = ref.watch(greetingProvider);
return Row(
children: [Text(greeting), ?child],
);
},
child: const Icon(Icons.waving_hand),
),
],
);
}
}The builder function receives three arguments: the context, the ref, and an optional child. The child is built once and handed back on every rebuild, which avoids reconstructing a subtree that does not depend on the provider. Passing a child is optional, so the parameter is nullable. The ?child syntax is a Dart null-aware element that adds the item to the list only when it is not null. It requires Dart 3.8 or later. On older SDKs, write if (child != null) child! instead.
ConsumerStatefulWidget and ConsumerState
When you need both a State object and providers, use ConsumerStatefulWidget. Its state class extends ConsumerState, which exposes ref as a property, so you can use it in any method of the state, not just in build.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');
class GreetingPage extends ConsumerStatefulWidget {
const GreetingPage({super.key});
@override
ConsumerState<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends ConsumerState<GreetingPage> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: ref.read(greetingProvider));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final greeting = ref.watch(greetingProvider);
return Scaffold(
body: Column(
children: [
Text(greeting),
TextField(controller: _controller),
],
),
);
}
}In initState, the code uses ref.read to take a one-time snapshot to seed the controller. A subscription made with watch there would not do what you expect, because initState runs only once. Reserve ref.watch for build.
Choosing a widget type
| Widget type | Replaces | Gives you `ref` in | Use it when |
|---|---|---|---|
| `ConsumerWidget` | `StatelessWidget` | The `build` parameter | The whole widget depends on providers and needs no local state |
| `Consumer` | A `Builder` inside any widget | The `builder` parameter | Only a small subtree depends on providers |
| `ConsumerStatefulWidget` | `StatefulWidget` | `ref` property on `ConsumerState` | You need `initState`, `dispose`, controllers, or animations along with providers |
If a widget already extends StatelessWidget and you only need a provider in one spot, Consumer avoids changing the class. If most of the build method uses providers, converting to ConsumerWidget is simpler and reads better.
Common errors
- Bad state: No ProviderScope found. The
ProviderScopeis missing above the widget that usesref. Wrap the app inrunApp(const ProviderScope(child: MyApp())). In widget tests, wrap the widget under test in aProviderScopeas well. - Using
refin a plainStatelessWidget. There is norefthere. Change the base class or wrap the part that needs it in aConsumer. - Calling
ref.watchin a callback. Code such asonPressed: () => ref.watch(...)is wrong. Riverpod throws an assertion error in debug mode in some cases, and in others it silently creates subscriptions you do not intend. Useref.readinside event handlers. - Using
refafter the widget is disposed. If you callref.readafter anawaitin a callback, checkcontext.mounted(ormountedin aState) first. Using a disposedrefthrows aStateError. - Rebuilding too much. Watching a provider at the top of a large page rebuilds the entire page on each change. Push the
ref.watchdown into a smallerConsumerWidgetor aConsumer.
Summary of the model
ProviderScope owns the state. A ConsumerWidget, Consumer, or ConsumerState gives a widget a WidgetRef to that state. Calling ref.watch inside build registers a dependency, and Riverpod rebuilds that widget when the watched value changes. Everything else you do with providers in the UI goes through the same ref object.
Exercise
A teammate writes class PriceTag extends StatelessWidget and, inside build, tries ref.watch(priceProvider). The code does not compile. Give two different ways to fix it, and say when you would choose each.
Show answer
First, change the base class to ConsumerWidget and change the signature to Widget build(BuildContext context, WidgetRef ref). Choose this when most of the widget depends on providers. Second, keep StatelessWidget and wrap only the part that needs the price in a Consumer(builder: (context, ref, child) { ... }). Choose this when only a small subtree depends on the provider, so the rest of the widget does not rebuild when the price changes.
Exercise
In a ConsumerStatefulWidget, you want to copy a provider's current value into a TextEditingController once when the screen opens. Which ref method do you use in initState, and why not ref.watch?
Show answer
Use ref.read(provider). initState runs only once, so it is a one-time snapshot, and ref.watch is meant for build, where Riverpod can rebuild the widget when the value changes.