In this blog we will learn about how to use Notification Center in Flutter.
Introduction
Notifications enhance user engagement and provide real-time updates in mobile applications.
They keep users informed about important events, such as new messages, reminders, or system updates.
Apps deliver notifications in different forms, including local alerts, push notifications, or in-app real-time data updates.
Why Use Notifications in Flutter?
In Flutter, you would use state management solutions like Provider, Bloc or setState
to manage the app’s state.
However, in cases where you need to notify different parts of your app about changes without direct dependencies between them, notifications provide a clean and efficient solution.
For instance, if you have a product list on one screen and a product detail view on another, and you want the “like” status of a product to update in both places, notifications make this process easy to manage.
Setting Up the Project:
Let’s get started with the project setup and see how we can implement the notification center pattern using the notification_center
package.
Implementation
Setting Up Your Flutter Project:
Open pubspec.yaml
and add the following dependencies under dependencies
and dev_dependencies
.
- Add Dependencies:
1 2 3 4 |
dependencies: flutter: sdk: flutter notification_center: ^1.0.0 # Add the notification_center package |
Run the following command to get the packages:
1 |
flutter pub get |
Using Notification Center in the Flutter Application:
Create the Main Product List Page:
In lib/main.dart
, create the main page (MainPage
) to display a list of products. Each product will include a like status, and the app will update this status by listening to notifications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
import 'package:flutter/material.dart'; import 'package:notification_centre/notification_centre.dart'; import 'productDetailsPage.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), initialRoute: '/', routes: { '/': (context) => MainPage(), ProductDetailsPage.routeName: (context) => ProductDetailsPage(), }, ); } } class Product { final int id; final String name; bool isLiked; Product({required this.id, required this.name, this.isLiked = false}); } class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { // List of products List<Product> products = [ Product(id: 1, name: "Product 1"), Product(id: 2, name: "Product 2"), Product(id: 3, name: "Product 3"), ]; @override void initState() { super.initState(); // Listen for updates to product like status NotificationCenter().addObserver('product_liked', this, (data) { setState(() { int productId = data['productId']; Product? product = products.firstWhere((p) => p.id == productId); product.isLiked = true; }); }); NotificationCenter().addObserver('product_unliked', this, (data) { setState(() { int productId = data['productId']; Product? product = products.firstWhere((p) => p.id == productId); product.isLiked = false; }); }); } @override void dispose() { NotificationCenter().removeObserver('product_liked', this); NotificationCenter().removeObserver('product_unliked', this); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Products List'), ), body: ListView.builder( itemCount: products.length, itemBuilder: (context, index) { final product = products[index]; return ListTile( leading: Icon( product.isLiked ? Icons.favorite : Icons.favorite_border, color: product.isLiked ? Colors.red : Colors.grey, ), title: Text(product.name), onTap: () { Navigator.pushNamed( context, ProductDetailsPage.routeName, arguments: product, ); }, ); }, ), ); } } |
Explanation of MainPage:
- We define a list of products, each with a
name
,id
, andisLiked
flag. - The Notification Center add observer method listens for two types of notifications: Product liked and product unliked. When a product’s like status changes, the app updates the UI accordingly.
- The ListView builder renders the product list, and tapping on a product navigates to the
ProductDetailsPage
.
Create the Product Details Page:
The Product Details page lets users like or unlike a product. When the like status changes, it sends a notification to update the main page.
Create a new file called productDetailsPage.dart
in the lib
folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import 'package:flutter/material.dart'; import 'package:notification_center/main.dart'; import 'package:notification_centre/notification_centre.dart'; class ProductDetailsPage extends StatefulWidget { static const routeName = "/productDetails"; @override _ProductDetailsPageState createState() => _ProductDetailsPageState(); } class _ProductDetailsPageState extends State<ProductDetailsPage> { late Product product; @override void didChangeDependencies() { super.didChangeDependencies(); product = ModalRoute.of(context)!.settings.arguments as Product; } void toggleLikeStatus() { setState(() { product.isLiked = !product.isLiked; if (product.isLiked) { // Notify the MainPage that the product is liked NotificationCenter().postNotification('product_liked', data: { 'productId': product.id, }); } else { // Notify the MainPage that the product is unliked NotificationCenter().postNotification('product_unliked', data:{ 'productId': product.id, }); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Product Details'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( product.name, style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold), ), SizedBox(height: 20), Icon( product.isLiked ? Icons.favorite : Icons.favorite_border, size: 100, color: product.isLiked ? Colors.red : Colors.grey, ), SizedBox(height: 20), ElevatedButton( onPressed: toggleLikeStatus, child: Text(product.isLiked ? 'Unlike' : 'Like'), style: ElevatedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 40, vertical: 15), textStyle: TextStyle(fontSize: 18), ), ), SizedBox(height: 20), TextButton( onPressed: () { Navigator.pop(context); }, child: Text('Back to Products List'), ), ], ), ), ); } } |
Explanation of ProductDetailsPage:
- This page receives a product object via route arguments.
- The user can like or unlike the product by pressing a button, which triggers the toggle like status method. This method sends a product liked or product unliked notification using the notification Center postNotification
- When the user returns to the main page, the app updates the product’s like status there as well.
Output:
Notification Center in Flutter
Notification Center in Flutter simplifies managing state updates across screens by allowing components to send and listen for notifications, enabling real-time updates like product status changes.
Handling Notifications:
The Notification Center package offers a straightforward way to manage notifications. Here’s how this project handles notifications:
- Adding Observers: NotificationCenter().addObserver is used in the
MainPage
to listen for notifications about product like/unlike actions. - Posting Notifications: In the
ProductDetailsPage
, NotificationCenter().postNotification is used to notify other parts of the app that a product’s status has changed. - Removing Observers: It’s important to clean up observers when they are no longer needed by calling NotificationCenter().removeObserver
Conclusion:
The Notification Center package in Flutter streamlines state management by facilitating communication between different screens.
It allows real-time updates, such as liking or unliking products, ensuring consistent data representation. This enhances the user experience by keeping the UI responsive to user actions.
And thanks for reading this blog for related data click here.
You can read more interesting blogs by mobikul .