Flutter
ConsumerWidget
Access ref with ConsumerWidget.
ConsumerWidget
ConsumerWidget is the widget used to access ref in Riverpod. It replaces StatelessWidget and adds a ref parameter to the build method.
class Screen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final value = ref.watch(nameP);
return Text(value);
}
}
ref is tied to the widget.
Listening with ref.watch
Inside ConsumerWidget, you listen to a provider with ref.watch(provider). When the provider changes, the build method is called automatically.
final count = ref.watch(counterP);
Text('$count');
When StateProvider's state changes, the widget updates.
Exercise Read provider with ConsumerWidget
Declare a Provider<String> named selamP returning 'Merhaba'. Make Ekrani a ConsumerWidget; in its build method, get the value with ref.watch(selamP) and display it as Text. In main, call print('ekran açıldı').
Show example solution
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final selamP = Provider<String>((ref) => 'Merhaba');
void main() {
print('ekran açıldı');
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Ekrani());
}
}
class Ekrani extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final selam = ref.watch(selamP);
return Scaffold(body: Center(child: Text(selam)));
}
}
Test yourself
-
How many parameters does ConsumerWidget's build method take?
- Only context
- context and ref
- Only ref
- None
Show answer
context and ref — ConsumerWidget's build method takes both context and WidgetRef ref parameters; this differs from StatelessWidget.
-
ConsumerWidget build signature
class Ekrani extends ConsumerWidget {
@override
Widget build(BuildContext context, ____ ref) {
return Container();
}
}
Show answer
class Ekrani extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return Container();
}
}
-
ConsumerWidget parts
- ConsumerWidget
- Riverpod alternative to StatelessWidget
- ref
- Object to access providers
- ref.watch
- Listens provider and triggers rebuild
- WidgetRef
- Type of the ref parameter
Next lesson: ProviderScope