Firebase Cloud Messaging (FCM)
Get Access Token
- Got to Google OAuth Playground: https://developers.google.com/oauthplayground
- In the "Input your own scopes" for FCM use this url:
https://www.googleapis.com/auth/firebase.messaging
- Tap Authorize API.
- Pick correct user for authorisation and allow access.
- In the Step 2: Exchange authorization code for tokens tap Exchange authorisation code for tokens.
- Access token is your Bearer.
config/fcm.dart
import 'dart:convert';
import 'dart:developer';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notif_fcm/config/local_notif.dart';
import 'package:flutter_local_notif_fcm/main.dart';
('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
log("background!");
_showCustomNotif(message);
}
void _handleMessage(RemoteMessage message) {
Map data = message.data;
if (data.containsKey('navigate_to')) {
navigatorKey.currentState?.pushNamed(data['navigate_to']);
}
}
void _showCustomNotif(RemoteMessage message) {
// if (message.notification != null) {
// LocalNotif.showNotif(
// id: message.hashCode,
// title: message.notification!.title,
// body: message.notification!.body,
// payload: jsonEncode(message.data),
// );
// }
if (message.data.containsKey('notif_title')) {
LocalNotif.showNotif(
id: message.hashCode,
title: message.data['notif_title'],
body: message.data['notif_body'],
payload: jsonEncode(message.data),
);
}
}
class FCM {
static Future<void> init() async {
await FirebaseMessaging.instance.setAutoInitEnabled(true);
final settings = await FirebaseMessaging.instance.requestPermission();
log('User granted permission: ${settings.authorizationStatus}');
_foregroundHandler();
_backgroundHandler();
_listenOpenNotif();
}
static _foregroundHandler() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
log('foreground!');
_showCustomNotif(message);
});
}
static _backgroundHandler() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}
// for terminate state
static initialMessage() async {
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
_handleMessage(initialMessage);
}
}
static _listenOpenNotif() {
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
}
}