ConsumerWidget and ref.watch
Part of the State Management section of Coddy's Flutter journey. Lesson 17 of 27.
Any widget can read a provider once it can get a ref. To give it one, change two things:
extends StatelessWidgetbecomesextends ConsumerWidget.buildgets a second parameter,WidgetRef ref.
class CityName extends ConsumerWidget {
const CityName({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final city = ref.watch(cityProvider);
return Text(city);
}
}ref.watch(cityProvider) gives you the provider's value, here the text Lisbon, and builds the widget again whenever that value changes. Without ref.watch, cityProvider is only the provider itself, not its value.
Each widget that needs a value asks for it like this, wherever it sits. Nothing is passed down through constructors, and nothing needs context to find it.
Challenge
EasyCityName and Temperature show placeholders. Make them read the providers at the top of the file:
- Turn both into
ConsumerWidgets. CityNameshows the value ofcityProvider.Temperatureshows the value oftemperatureProviderfollowed by°C, at the same size.
Try it yourself
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final cityProvider = Provider((ref) => 'Lisbon');
final temperatureProvider = Provider((ref) => 21);
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const CityName()),
body: const Center(child: Temperature()),
),
);
}
}
class CityName extends StatelessWidget {
const CityName({super.key});
@override
Widget build(BuildContext context) {
return const Text('City');
}
}
class Temperature extends StatelessWidget {
const Temperature({super.key});
@override
Widget build(BuildContext context) {
return const Text('0°C', style: TextStyle(fontSize: 64));
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in State Management
1Lifting State Up
Pass State to a ChildPass a Callback to a ChildCallbacks That Send a ValueLift State Up4Riverpod
Riverpod: ProviderScopeConsumerWidget and ref.watchRiverpod: StateProviderRiverpod: NotifierProviders That Watch ProvidersChoosing Where State LivesPractice on your own: Online Flutter compiler