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 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.

void main() {   runApp(     MultiProvider(       providers: [         ChangeNotifierProvider(           create: (_) => Books(),         ),         ChangeNotifierProvider(           create: (_) => Cart(),         ),         ChangeNotifierProvider(           create: (_) => Orders(),         ),       ],       child: const BookApp(),     ),   ); } class BookApp extends StatelessWidget {   const BookApp({Key? key}) : super(key: key);    @override   Widget build(BuildContext context) {     return MaterialApp(       title: 'Book Shop',       theme: ThemeData(         primarySwatch: Colors.purple,         primaryColor: Colors.deepOrange,       ),       home: const BooksOverviewScreen(),       routes: {         BookDetailScreen.routeName: (ctx) => const BookDetailScreen(),       },     );   } }  // for full code please visit the original article on my website


This free site is ad-supported. Learn more