Reputation: 39
Can I using the ChangeNotifierProvider on the top of my app tree? is it a good practice in Flutter?
Also running the MyApp Widget as Stateful widget is a good practice?
class _MyAppState extends State<MyApp> {
@override
void initState() {
PushNotificationService.messageStream.listen((message) {
//some code
});
super.initState();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => MyProvider(),
child: MaterialApp(
//more code
),
);
}
}
Upvotes: 1
Views: 687
Reputation: 4404
StatelessWidget
in all flutter App. but also when you need to have a initial state, or local state variable, its will be better to use StatefullWidget
. So... use as you need.ChangeNotifierProvider
on top of tree is a common practice.see here official example from docs.flutter.dev, they put inside main function.
https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple#changenotifierprovider
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CartModel(),
child: const MyApp(),
),
);
}
the things that we have to avoid while using provider is with the Consumer
at the top of widget tree.
read here : https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple#consumer
It is best practice to put your Consumer widgets as deep in the tree as possible. You don’t want to rebuild large portions of the UI just because some detail somewhere changed.
when we called the notifyListeners();
this will rebuild current Consumer
widget. when you use it on Top of tree, everytime receive notifylistener your widget Tree will rebuild from the Consumer below.
You can see the example here : https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple#consumer
Upvotes: 1