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
),
);
}
}
StatelessWidget
in all flutter App. but also when you need to have a initial state, or local state variable, its will be better to useStatefullWidget
. 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
;TLDR
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
when we called the
notifyListeners();
this will rebuild currentConsumer
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