Flutter
ChangeNotifierProvider
Provide the model to the tree with ChangeNotifierProvider.
ChangeNotifierProvider
ChangeNotifierProvider provides a ChangeNotifier model to the widget tree. The create parameter takes the function that produces the model, and the model is managed automatically.
ChangeNotifierProvider<CounterModel>(
create: (_) => CounterModel(),
child: MaterialApp(home: Screen()),
)
The model is automatically disposed when it leaves the tree.
create and child
create is called when the provider is first needed and returns a ChangeNotifier instance. child is the widget subtree under the provider.
ChangeNotifierProvider<CounterModel>(
create: (_) => CounterModel(),
child: Screen(),
)
The model's lifecycle is managed by the provider.
Exercise Provide model with ChangeNotifierProvider
Provide the model to the tree with ChangeNotifierProvider<SayacModeli>. Create a new SayacModeli() instance with create. In main, call print('uygulama açıldı').
Show example solution
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
print('uygulama açıldı');
runApp(MyApp());
}
class SayacModeli extends ChangeNotifier {
int deger = 0;
}
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) {
return Scaffold(
body: Center(child: Text('ekran')),
);
}
}
Test yourself
-
What does the create parameter of ChangeNotifierProvider do?
- Defines the function that produces the model
- Triggers hot reload
- Only paints the widget
- Restarts the app
Show answer
Defines the function that produces the model — The create parameter takes the function that produces the model instance when ChangeNotifierProvider is first needed.
-
Complete ChangeNotifierProvider's create
ChangeNotifierProvider<SayacModeli>(
____: (_) => SayacModeli(),
child: Ekrani(),
)
Show answer
ChangeNotifierProvider<SayacModeli>(
create: (_) => SayacModeli(),
child: Ekrani(),
)
-
ChangeNotifierProvider parts
- ChangeNotifierProvider
- Widget providing ChangeNotifier to tree
- create
- Function producing model instance
- child
- Widget subtree under provider
- dispose
- Called when model leaves tree
Next lesson: context.watch and read