Flutter
context.watch and read
Learn the difference between context.watch and context.read.
context.watch
context.watch<T>() listens to the provided model and automatically rebuilds the widget when notifyListeners is called. It is used inside the build method.
final model = context.watch<CounterModel>();
Text('${model.value}')
On every change, build runs again.
context.read
context.read<T>() reads the model once without listening. Even if notifyListeners is called, it does not trigger a rebuild. It is used outside build, such as in button callbacks.
onPressed: () {
context.read<CounterModel>().increment();
}
Unlike watch, read does not trigger build.
Exercise Listen with watch, call with read
In Ekrani, get the model with context.watch<SayacModeli>() and display deger. When the button is pressed, call context.read<SayacModeli>().artir(). In main, call print('ekran hazır').
Show example solution
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
print('ekran hazır');
runApp(MyApp());
}
class SayacModeli extends ChangeNotifier {
int deger = 0;
void artir() {
deger++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<SayacModeli>(
create: (_) => SayacModeli(),
child: MaterialApp(home: Ekrani()),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = context.watch<SayacModeli>();
return Scaffold(
body: Center(child: Text('${model.deger}')),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.read<SayacModeli>().artir();
},
child: Icon(Icons.add),
),
);
}
}
Test yourself
-
What is the difference between context.watch and context.read?
- watch is only used in initState
- They are exactly the same
- watch listens and rebuilds, read reads only once
- read rebuilds, watch only reads
Show answer
watch listens and rebuilds, read reads only once — context.watch listens to the model and triggers rebuild on change; context.read reads once without listening.
-
Read the model once inside the button
onPressed: () {
context.____<SayacModeli>().artir();
}
Show answer
onPressed: () {
context.read<SayacModeli>().artir();
}
-
watch and read parts
- context.watch
- Triggers rebuild on change
- context.read
- Reads once without listening
- build metodu
- Where watch is used
- onPressed
- Where read can be used
Next lesson: Summary - Provider