Home > OS >  is adding ChangeNotifierProvider Widget as Parent of MaterialApp a Flutter Best Practice?
is adding ChangeNotifierProvider Widget as Parent of MaterialApp a Flutter Best Practice?

Time:01-27

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
      ),
    );
  }
}

CodePudding user response:

It is a good practice to use the ChangeNotifierProvider at the top of your app tree, as it allows for easy access to the provider's data and methods throughout the entire app. This allows you to keep the state of your app in a centralized location, making it easier to manage and update.

Regarding the MyApp Widget as Stateful widget, it depends on the requirement of your app. If your app needs to hold some state that can change during the lifetime of the app, then it is good practice to use a StatefulWidget. If your app does not need to hold any state that can change during the lifetime of the app, then you can use StatelessWidget.

CodePudding user response:

  • Its better to priority to use 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.

  • I would said that using 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(),
    ),
  );
}

;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

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

  • Related