Now all setup is done to work with Pushnotification
firebase_core: ^1.12.0
firebase_messaging: ^11.2.6
flutter_local_notifications: ^9.2.0
Firebase : https://console.firebase.google.com/
NOTE : -> After setup firebase project you can receive simple pushnotification from firebase cloud messaging without doing anything additional if you just want to display notifications to users in your app. When user taps on your notification your app will be opened. But if you want to open some specific screen or you want to customize the appearence of your notification then follow along:
main.dart
main() {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
}
- add this method after import statement in main.dart
Future<void> backgroundHandler(RemoteMessage message) async {
print(message.data.toString());
print(message.notification!.title);
}
- call this method from main method after await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
@override
void initState() {
super.initState();
// 1. This method call when app in terminated state and you get a notification
// when you click on notification app open from terminated state and you can get notification data in this method
FirebaseMessaging.instance.getInitialMessage().then(
(message) {
print("FirebaseMessaging.instance.getInitialMessage");
if (message != null) {
print("New Notification");
// if (message.data['_id'] != null) {
// Navigator.of(context).push(
// MaterialPageRoute(
// builder: (context) => DemoScreen(
// id: message.data['_id'],
// ),
// ),
// );
// }
}
},
);
// 2. This method only call when App in forground it mean app must be opened
FirebaseMessaging.onMessage.listen(
(message) {
print("FirebaseMessaging.onMessage.listen");
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
print("message.data11 ${message.data}");
// LocalNotificationService.display(message);
}
},
);
// 3. This method only call when App in background and not terminated(not closed)
FirebaseMessaging.onMessageOpenedApp.listen(
(message) {
print("FirebaseMessaging.onMessageOpenedApp.listen");
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
print("message.data22 ${message.data['_id']}");
}
},
);
}
7) after all these you send a notification when your app in background then you see some warning in console when you tap on notification like this
Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
Because of this warning you are not getting notification like we get in youtube and other app. To solve this add below line in AndroidManifest.xml:
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="pushnotificationapp"/>
8) After donign this you get another warning (this warning will show when you send notification with channel name pushnotificationapp
Notification Channel requested (pushnotificationapp) has not been created by the app. Manifest configuration, or default, value will be used
so now we need to create a channel with name pushnotificationapp we do it with the help of flutter local notification
9) Go inside lib -> create folder -> notificationservice -> create file inside notificationservice -> local_notification_service.dart
go inside the local_notification_service.dart and create a class
class LocalNotificationService{
// inside class create instance of FlutterLocalNotificationsPlugin see below
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
// after this create a method initialize to initialize localnotification
static void initialize(BuildContext context) {
// initializationSettings for Android
const InitializationSettings initializationSettings =
InitializationSettings(
android: AndroidInitializationSettings("@mipmap/ic_launcher"),
);
_notificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (String? id) async {
print("onSelectNotification");
if (id!.isNotEmpty) {
print("Router Value1234 $id");
// Navigator.of(context).push(
// MaterialPageRoute(
// builder: (context) => DemoScreen(
// id: id,
// ),
// ),
// );
}
},
);
}
// after initialize we create channel in createanddisplaynotification method
static void createanddisplaynotification(RemoteMessage message) async {
try {
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
const NotificationDetails notificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
"pushnotificationapp",
"pushnotificationappchannel",
importance: Importance.max,
priority: Priority.high,
),
);
await _notificationsPlugin.show(
id,
message.notification!.title,
message.notification!.body,
notificationDetails,
payload: message.data['_id'],
);
} on Exception catch (e) {
print(e);
}
}
}
LocalNotificationService.initialize(); and uncomment last line from FirebaseMessaging.onMessage method in homescreen
Future<void> getDeviceTokenToSendNotification() async {
final FirebaseMessaging _fcm = FirebaseMessaging.instance;
final token = await _fcm.getToken();
deviceTokenToSendPushNotification = token.toString();
print("Token Value $deviceTokenToSendPushNotification");
}
go to Headers section and set Header
Content-Type -> application/json
Authorization ->key=YOUR_SERVER_KEY
1. method post
2. API Url -> https://fcm.googleapis.com/fcm/send
3. json Body ->
{
"registration_ids": [
"dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
],
"notification": {
"body": "New Video has been uploaded",
"title": "Inventorcode",
"android_channel_id": "pushnotificationapp",
"sound": false
}
}
add data key in josn like this
{
"notification"{
}
"data":{"_id":1}
}
"registration_ids": [
"dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
]
NOTE ->>>>>>>>>>> If you want to send image in notification add "image":"", key in "":{"notification":""},
{
"registration_ids": [
"dJVh8FWXQ_2ipxYVpFaXCT:APA91bFyHc6mSyWHMgN7_iVDk5zB1WwB6qKlZGcxIpRBFnnxl4CRRi9qTCD3oLrJU6OY12AGzuM8_XZkEiWuwXUMc8nIlupjfrjIgNdzuhmq3bAOBYdw1z_8nmcSWyFNin24jkfgFTC5"
],
"notification": {
"body": "New Video has been uploaded",
"title": "Inventorcode",
"android_channel_id": "pushnotificationapp",
"image":"https://cdn2.vectorstock.com/i/1000x1000/23/91/small-size-emoticon-vector-9852391.jpg",
"sound": false
}
}