Sanjib Sinha posted: " Photo by Kamila Maciejewska on Unsplash What is change notifier provider in Flutter? ChangeNotifierProvider is a class that comes with the Provider package. Although I've written about change notifier before, yet this article is all together di"
ChangeNotifierProvider is a class that comes with the Provider package. Although I've written about change notifier before, yet this article is all together different.
We're going to build a Book Shopping Cart flutter app, and to maintain state we've used Provider package for the best result and less widget rebuilds.
To sum up, ChangeNotifierProvider listens to a ChangeNotifier. Not only listening but it also expose ChangeNotifier to its descendants and rebuilds dependents when the state changes.
When does state change?
As ChangeNotifier notifies its listeners, the state changes.
import 'package:flutter/foundation.dart'; class Book with ChangeNotifier { final String id; final String title; final String description; final double price; final String imageUrl; bool isFavorite; Book({ required this.id, required this.title, required this.description, required this.price, required this.imageUrl, this.isFavorite = false, }); void toggleFavoriteStatus() { isFavorite = !isFavorite; notifyListeners(); } }
The above code means when we click the favorite icon on the Book item, the ChangeNotifier notify the listeners.
Now, question is what is the correct way to create a ChangeNotifier?
According to the documentation provided by the Provider package ChangeNotifierProvider, the following way is the correct way.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.