Sub topic 3
Your first provider: exposing a read-only value
A provider is the basic building block of Riverpod. This chapter covers the simplest kind, Provider<T>, which exposes a value that your widgets can read but never change directly. It assumes you know Dart classes, generics and closures, and that you can write a Flutter StatelessWidget and its build method. Later chapters cover mutable state. Here you learn how a provider is declared, created, cached and read.
What a Provider is
A Provider<T> is a small object that knows how to create one value of type T. You give it a function, and Riverpod calls that function the first time something asks for the value. Riverpod stores the result and hands back the same value on later reads.
Three facts follow from this:
- The provider declaration describes how to build a value. It does not hold the value itself.
- The value lives in a
ProviderContainer. In a Flutter app, theProviderScopewidget at the root creates and owns this container. - Because widgets only read the value, a plain
Providerhas no way to be updated from outside.
A complete first example
This program declares a provider, installs ProviderScope, and displays the value in a ConsumerWidget.
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))),
);
}
}Go through it in order.
greetingProvideris a top-levelfinalvariable. The type argument<String>is the type of the value it exposes.- The closure
(ref) => 'Hello, Riverpod'is the creation function. It receives aRef, which you will use later to read other providers. ProviderScopewraps the app, so every widget below it can reach the container.MyAppextendsConsumerWidget. Itsbuildmethod receives a second parameter,WidgetRef ref, which is how a widget talks to providers.ref.watch(greetingProvider)returns the string. It also tells Riverpod to rebuild this widget if the value ever changes.
Why the provider is a global variable
A top-level final can look like a global singleton, which is usually a design smell. Here it is safe because the variable holds no state. It holds a recipe, and the state lives in the container. Two containers created from the same provider variable have two independent values. This is what makes testing possible: each test creates its own container.
The sequence below shows what happens on the first read.
Two properties of this flow matter in practice:
- Lazy creation. The create function does not run when the app starts. It runs when something first reads the provider. A provider that nobody reads never runs.
- Caching. The create function runs once per container, unless something it depends on changes or the provider is disposed or invalidated. Later chapters cover those cases.
What belongs in a plain Provider
A read-only provider fits any value that widgets need but do not mutate. Common uses:
| Use | Example value |
|---|---|
| Configuration | An `AppConfig` with a base URL |
| A service or repository | An object that wraps an HTTP client |
| A function | A clock, an ID generator |
| A computed constant | A formatter built once |
The last two rows are worth a closer look. Exposing a service through a provider is how Riverpod does dependency injection. Widgets ask for the service by provider, never by constructing it, so you can replace it later without touching widget code.
Exposing a dependency you can replace
Time is a classic hidden dependency. Code that calls DateTime.now() directly is hard to test. A provider that exposes the function fixes that.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final clockProvider = Provider<DateTime Function()>((ref) => DateTime.now);
class YearLabel extends ConsumerWidget {
const YearLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final now = ref.watch(clockProvider);
return Text('Year: ${now().year}');
}
}
void main() {
runApp(
ProviderScope(
overrides: [
clockProvider.overrideWithValue(() => DateTime(2030, 1, 1)),
],
child: const MaterialApp(
home: Scaffold(body: Center(child: YearLabel())),
),
),
);
}The provider's value is the function DateTime.now itself, not a timestamp, so it is never stale. In main, the overrides list on ProviderScope replaces the real clock with a fixed one, and the label shows Year: 2030. The widget has no idea the value was swapped. This is the same mechanism you will use for fake repositories in the testing chapter.
Provider with a non-trivial value
The create function can build any object. This example groups two settings into one value object.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class AppConfig {
const AppConfig({required this.appName, required this.apiBaseUrl});
final String appName;
final String apiBaseUrl;
}
final appConfigProvider = Provider<AppConfig>((ref) {
return const AppConfig(
appName: 'Notes',
apiBaseUrl: 'https://api.example.com',
);
});Any widget can then call ref.watch(appConfigProvider).apiBaseUrl. When a provider like this grows to depend on other providers, you will read them through the ref parameter. That is the subject of the chapter on deriving state.
Common mistakes
Forgetting ProviderScope. If no ProviderScope sits above the widget, Riverpod cannot find a container and the read fails with an error at runtime. Put it directly in runApp.
Declaring providers inside build. A provider declared inside a method is a new object on every build, so it never shares state or cache. Declare providers at the top level of a file.
Trying to change the value. A plain Provider has no setter. If you find yourself wanting to assign to it, the value is mutable state, and you need NotifierProvider, which comes in a later chapter.
Using it for work that changes. Do not return a value that goes stale, such as a timestamp captured at creation. Expose a function, as clockProvider does, or use a provider type built for changing data.
Reading a provider from the wrong place. Inside build, use ref.watch. The next chapter explains when ref.read is the right choice.
Summary of the model
Provider<T>(create)declares how to build a read-onlyT.- The value is created lazily and cached in the
ProviderContainerowned byProviderScope. - Widgets read it with
ref.watchfrom aConsumerWidget. - Exposing services and functions through providers makes them replaceable with overrides.
Exercise
A teammate writes final loggerProvider = Provider<Logger>((ref) => Logger()); at the top of a file and reads it in two different widgets with ref.watch. How many Logger objects does Riverpod create, and when is the first one created? What changes in a test that creates two separate ProviderContainers?
Show answer
Within one container, Riverpod creates a single Logger. It is created lazily, the first time any widget reads loggerProvider, and both widgets then receive the same cached instance. Two separate ProviderContainers each run the create function themselves, so a test gets two independent Logger objects, one per container, and the provider variable itself holds no state.
Exercise
You need a provider that returns the current time. Why is Provider<DateTime>((ref) => DateTime.now()) a poor choice, and what should you write instead?
Show answer
The create function runs once and the result is cached, so the provider keeps returning the time from the first read and the value goes stale. Expose the function instead, for example Provider<DateTime Function()>((ref) => DateTime.now), and call it where the time is needed. This also lets a test override the provider with a fixed clock.