flutterdartflutter-change-notifier-provider

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


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

Solution


  • 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