Difference Between ChangeNotifierProvider & ChangeNotifierProvider.value.
A Class that extends ChangeNotifier can call notifyListeners() any time data in that class. So, in this article, we will see the Difference in ChangeNotifierProvider & ChangeNotifierProvider.value.
Difference in ChangeNotifierProvider & ChangeNotifierProvider.value.
When you’re using Provider in a single list or grid item, flutter removes items when they leave the screen. After then it re-adds them when they reentered the screen. Also, it will reuse the widget.
So, flutter recycles the same widget and it doesn’t destroy it. Later it recreates it when we are using Provider with the create function.
What is ChangeNotifierProvider?
Consider a code snippet as below to understand ChangeNotifierProvider.
class MyChangeNotifier extends ChangeNotifier { int _counter = 0; int get counter => _counter; void increment() { _counter++; notifyListeners(); } }
ChangeNotifierProvider is one of many types of providers in the Provider package. If you already have a ChangeNotifier class like the one above, then you can use ChangeNotifierProvider to provide it to the place you need it in the UI layout.
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider<MyChangeNotifier>( // define it create: (context) => MyChangeNotifier(), // create it child: MaterialApp( ... child: Consumer<MyChangeNotifier>( // get it builder: (context, myChangeNotifier, child) { ... myChangeNotifier.increment(); // use it
Also, note that it created a new instance of the MyChangeNotifier class in this line:
create: (context) => MyChangeNotifier(),
It will create a new instance when the widget is first built.
ChangeNotifierProvider( create: (_) => new MyChangeNotifier(), child: ... )
Moreover, here content changes over time and our provider won’t pick us up. So in a single list or grid item, we should use the Provider dot value.
ChangeNotifierProvider.value( value: new MyChangeNotifier(), child: ... )
Conclusion:
Thanks for being with us on a Flutter Journey!
So, in this article, we have seen the Difference in ChangeNotifierProvider & ChangeNotifierProvider.value. Also, feel free to comment and provide any other suggestions regarding Flutter.
Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. Also, the portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.