Push notification
Push notifications are a crucial feature for engaging users and keeping them informed about updates in your Flutter app. This documentation provides a step-by-step guide to implementing push notifications in your Flutter app using Firebase Cloud Messaging (FCM)
Prerequisites
1.Flutter development environment set up.
2.An active Firebase project.
Setting Up Firebase
1.Create a new project on Firebase Console.
2.Add your Android and iOS app to the project using their respective package names and bundle IDs.
3.Download and add the google-services.json (for Android) and GoogleService-Info.plist (for iOS) files to your app's respective directories as indicated previously in Google Authentication
Adding Dependencies
In your pubspec.yaml file, add the Firebase Cloud Messaging dependency:
firebase_core: ^1.10.6
firebase_messaging: ^10.3.4
Configuring Push Notifications
Initialize Firebase in your main.dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Request notification permissions and handle incoming messages in your app:
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
void initState() {
super.initState();
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(
onMessage: (Map message) async {
print("onMessage: $message");
// Handle foreground notifications
},
onLaunch: (Map message) async {
print("onLaunch: $message");
// Handle launch notifications
},
onResume: (Map message) async {
print("onResume: $message");
// Handle resume notifications
},
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Push Notifications Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Push Notifications Demo'),
),
body: Center(
child: Text('Welcome to Push Notifications Demo'),
),
),
);
}
}
Handling Notifications
Foreground Notifications (onMessage): Notifications received when the app is in the foreground. Handle these notifications within the onMessage callback.
Background Notifications (onLaunch): Notifications received when the app is terminated. Handle these notifications within the onLaunch callback.
Resumed Notifications (onResume): Notifications received when the app is in the background but resumed. Handle these notifications within the onResume callback.
Send Push Notifications from Firebase Console
You can send push notifications to your app users using Firebase Cloud Messaging console or programmatically via the FCM API.
For example, to send a notification using the Firebase Cloud Messaging console:
1.Log in to the Firebase Console.
2.Select your project and navigate to the "Cloud Messaging" section.
3.Click "New Notification."
Customize your notification and target audience.
Click "Send."
For programmatic notifications, use the FCM API to send messages from your server to FCM, which then delivers the messages to the appropriate devices.
Send Push Notifications from Nodejs server
Sending push notifications from a Node.js server to a Flutter app using Firebase Cloud Messaging (FCM) involves using the FCM API. Here's a step-by-step guide on how to achieve this
Set Up Firebase:
If you haven't already, create a Firebase project and configure your Flutter app to receive push notifications. Follow the steps mentioned in the "Setting Up Firebase" section of the previous documentation.
obtain FCM Server Key:
To send push notifications from your Node.js server, you'll need to obtain the FCM Server Key:
Go to the Firebase Console.
Select your project and navigate to "Project settings" > "Cloud Messaging."
Copy the "Server key."
Install the firebase-admin package to interact with FCM from your Node.js server.
npm install firebase-admin
Send Push Notifications:
Use the firebase-admin package to send push notifications from your Node.js server. Here's an example code snippet:
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK with your service account key
const serviceAccount = require('./path-to-your-service-account-key.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// Set the recipient device token
const deviceToken = 'YOUR_DEVICE_TOKEN';
// Define the push notification message
const message = {
notification: {
title: 'Notification Title',
body: 'Notification Body',
},
token: deviceToken,
};
// Send the push notification
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent push notification:', response);
})
.catch((error) => {
console.error('Error sending push notification:', error);
});