How to display notification in app in flutter - flutter

I'm trying to display the background and foreground notification in flutter using flutter_local_notifications package. here is my firebase class code
class FirebaseMessagingService {
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
IOSInitializationSettings? _initializationSettingsIOS;
AndroidInitializationSettings? _initializationSettingsAndroid;
AndroidNotificationDetails? _androidLocalNotificationDetails;
AndroidNotificationChannel? androidNotificationchannel;
static FirebaseMessagingService? _messagingService;
NotificationDetails? _androidNotificationDetails;
InitializationSettings? _initializationSettings;
//NotificationNavigationClass _notificationNavigationClass = NotificationNavigationClass();
NotificationAppLaunchDetails? _notificationAppLaunchDetails;
bool? _didNotificationLaunchApp;
static FirebaseMessaging? _firebaseMessaging;
FirebaseMessagingService._createInstance();
factory FirebaseMessagingService() {
// factory with constructor, return some value
if (_messagingService == null) {
_messagingService = FirebaseMessagingService
._createInstance(); // This is executed only once, singleton object
_firebaseMessaging = _getMessagingService();
}
return _messagingService!;
}
static FirebaseMessaging _getMessagingService() {
return _firebaseMessaging ??= FirebaseMessaging.instance;
}
Future<String?> getToken() {
return _firebaseMessaging!.getToken();
}
Future initializeNotificationSettings() async
{
NotificationSettings? settings = await _firebaseMessaging
?.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (settings?.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else
if (settings?.authorizationStatus == AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('User declined or has not accepted permission');
}
androidNotificationchannel = const AndroidNotificationChannel(
NOTIFICATION_ID, // id
NOTIFICATION_TITLE, // title
description: NOTIFICATION_DESCRIPTION,
// description
importance: Importance.max,
);
//
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(androidNotificationchannel!);
if (Platform.isIOS) {
//configure local notification for ios
await _initializeIosLocalNotificationSettings();
}
else {
//configure local notification for android
await _initializeAndroidLocalNotificationSettings();
}
}
Future<void> _initializeIosLocalNotificationSettings() async
{
_initializationSettingsIOS = const IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false
);
_initializationSettings = InitializationSettings(
iOS: _initializationSettingsIOS
);
}
Future<void> _initializeAndroidLocalNotificationSettings() async
{
_initializationSettingsAndroid =
const AndroidInitializationSettings('mipmap/ic_launcher');
_initializationSettings = InitializationSettings(
android: _initializationSettingsAndroid,
);
_androidLocalNotificationDetails =
const AndroidNotificationDetails(
LOCAL_NOTIFICATION_ID,
LOCAL_NOTIFICATION_TITLE,
channelDescription: LOCAL_NOTIFICATION_DESCRIPTION,
importance: Importance.max,
priority: Priority.high);
_androidNotificationDetails =
NotificationDetails(android: _androidLocalNotificationDetails);
//This will execute when the app is open and in foreground
void foregroundNotification() {
try {
_showLocalNotification(localNotificationId: DateTime
.now()
.hour + DateTime
.now()
.minute + DateTime
.now()
.second,
notificationData: message?.data,
messageTitle:message?.notification?.title ,
messageBody: message?.notification?.body,
);
} catch (error) {
log("error");
}
});
}
void _showLocalNotification(
{int? localNotificationId, Map<String, dynamic>? notificationData,String? messageTitle,String? messageBody}) async
{
if (notificationData != null) {
log("Notification Data:${notificationData}");
await _flutterLocalNotificationsPlugin.show(
localNotificationId ?? 0, notificationData["title"]??messageTitle,
notificationData["body"]??messageBody,
_androidNotificationDetails,
payload: jsonEncode(notificationData));
}
}
//This will excute when the app is in background but not killed and tap on that notification
void backgroundTapNotification() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage? message) async {
try {
RemoteMessage? terminatedMessage = await _firebaseMessaging
?.getInitialMessage();
} catch (error) {
log("error");
}
});
}
}
and calling it in splash screen
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 500));
heartbeatAnimation =
Tween<double>(begin: 100.0, end: 250.0).animate(controller);
controller.forward().whenComplete(() {
controller.reverse();
});
void _setNotifications() async {
FirebaseMessagingService().foregroundNotification();
FirebaseMessagingService().backgroundTapNotification();
}
await FirebaseMessagingService().initializeNotificationSettings();
_setNotifications();
}
When i close the app and hit the API notification is displaying on background, but when i open the app and hit the API notification is not displaying, nor foreground and not on background.
please help me to get out from this problem.

Related

how to disable push notifications by condition in Flutter?

I have an application, I want to send notifications only to authorized users,
authorization occurs by token if the token is empty, then the user is not authorized, for authorization and storing the token I use the shared_pref package. How can I disable notifications if the user is not logged in?
Token validation is only done in MyAppState notifications I need to disable in the same place
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await Permission.notification.request();
if(Constants.USER_TOKEN.isEmpty) {
FirebaseMessaging.instance.setAutoInitEnabled(false);
}
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
if (navKey.currentState != null) {
if(Constants.USER_TOKEN.isNotEmpty) {
navKey.currentState!.push(MaterialPageRoute(
builder: (context) => NotificationScreen()));
}
print('Message');
}
}
await _messaging.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification!.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
icon: '#mipmap/ic_launcher',
),
),
);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage? message) {
print("On message opened app: ${message?.data}}");
if (navKey.currentState != null) {
if(Constants.USER_TOKEN.isNotEmpty) {
navKey.currentState!.push(MaterialPageRoute(
builder: (context) => const NotificationScreen()));
}
}
});
var initializationSettingsAndroid =
const AndroidInitializationSettings('#drawable/ic_notification');
var initializationSettingsIOS = const DarwinInitializationSettings();
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await _messaging.requestPermission();
String? token = await _messaging.getToken();
if (token != null) {
print("FIREBASE TOKEN $token");
} else {
print("CANNOT TAKE FIREBASE TOKEN");
}
if (Platform.isIOS) {
var APNS = await _messaging.getAPNSToken();
print('APNS: $APNS');
}
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
getToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
Constants.USER_TOKEN = pref.getString('login') ?? "";
});
}
#override
void didChangeDependencies() async {
super.didChangeDependencies();
await getToken();
}
Use deleteToken which invalidates the current token and getToken again to get a new one when enabling.
getToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
Constants.USER_TOKEN = pref.getString('login') ?? "";
});
if(Constants.USER_TOKEN.isEmpty()){
// delete firebase token
}else{
// get firebase token
}
}

How to get image notifications when we trigger notifications from postman?

I am integrating notifications into my applications. Initially, I used firebase I got image notifications in 3 states i.e., on foreground(Local Notifications) background, and terminated state. But when I trigger a notification from postman I am getting a notification for the foreground. But in the background and terminated state, I am getting plain notifications with no image. I am getting the image URL in the data.
import 'dart:convert';
import 'package:authentication/utils/shared_utils.dart';
import 'package:authentication/utils/utils.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../presentation/authentication/login/login_view.dart';
import 'package:authentication/utils/routes/routes.dart';
class NotificationHelper {
FirebaseMessaging messaging = FirebaseMessaging.instance;
String notificationText;
AndroidBitmap androidBitmap;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.max,
playSound: true);
Future initializeFCM(String userId) async {
_initSettings(userId);
///handle messages when app is in foreground
_handleAndroidForegroundNotification();
_handleIosForegroundNotification();
///handle messages when app opened either from background or terminated state.
_onMessageOpened();
_onTerminated();
}
_initSettings(String userId) {
String uId = userId + "userSpecific";
messaging.subscribeToTopic("public");
messaging.subscribeToTopic(uId);
messaging.getToken().then((value) {
print("fcm token >>> " + value);
});
final AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
requestBadgePermission: false,
requestAlertPermission: false,
onDidReceiveLocalNotification: _onDidReceiveLocalNotification,
);
final InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
macOS: null);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: _onSelectNotification);
}
Future<dynamic> _onSelectNotification(data) async {
debugPrint("OnSelect Message Log>>>>>>>.");
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', data);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(data));
}
}
Future _onDidReceiveLocalNotification(
int id, String title, String body, String payload) async {
debugPrint("Did receive Message Log>>>>>>>.");
}
///handle foreground state for Android
Future _handleAndroidForegroundNotification() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
_showAndroidNotification(message);
});
}
///handle foreground state for iOS
Future _handleIosForegroundNotification() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
///handle background state
Future _onMessageOpened() async {
FirebaseMessaging.onMessageOpenedApp.listen((message) {
debugPrint('onMessageOpenedApp clicked!>>>>>>>>>.');
final routeFromMessage = message.data["route"];
debugPrint('Route called for background***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext, rootNavigator: true)
.push(Routes.generateRoute(routeFromMessage));
}
});
}
///handle terminated state
static _onTerminated() {
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
final routeFromMessage = message.data["route"];
debugPrint('Route called for terminated state***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(routeFromMessage));
}
}
});
}
/// set data to the notification UI
Future _showAndroidNotification(RemoteMessage message) async {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
androidBitmap = null;
if (message.data['image'] != null && message.data['image'] != '') {
var imagesBytes = await Utils.getImageBytes(message.data['image']);
androidBitmap =
ByteArrayAndroidBitmap.fromBase64String(base64.encode(imagesBytes));
} else if (message.notification.android.imageUrl != null) {
var imagesBytes =
await Utils.getImageBytes(message.notification.android.imageUrl);
androidBitmap =
ByteArrayAndroidBitmap.fromBase64String(base64.encode(imagesBytes));
}
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
color: Colors.blue,
styleInformation: androidBitmap != null
? BigPictureStyleInformation(androidBitmap)
: null,
playSound: true,
icon: '#mipmap/ic_launcher',
),
),
payload: message.data["route"]);
}
}
}

I am not getting image in push notifications when I triggered it from firebase

The below is the code for notification. Can anyone say what is the mistake or is there any code to add to get the image displayed in notification tray. I am using local notifications plugin to get the notifications. The below is the code for notification. Can anyone say what is the mistake or is there any code to add to get the image displayed in notification tray. I am using local notifications plugin to get the notifications.
class LocalNotificationService {
static var userId = SharedUtils.getString('UserId');
FirebaseMessaging messaging = FirebaseMessaging.instance;
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
static getText() {
String title;
String body;
}
static void initialize(BuildContext context) {
final InitializationSettings initializationSettings =
InitializationSettings(
android: AndroidInitializationSettings("#mipmap/ic_launcher"),
iOS: IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false));
_notificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String route) async {
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', route);
Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(route));
}
});
}
static Future initializeFCM(String userId) async {
String uId = userId + "userSpecific";
FirebaseMessaging.instance.subscribeToTopic("public");
FirebaseMessaging.instance.subscribeToTopic(uId);
print(">>>>>>> fcm started $uId");
FirebaseMessaging.instance.getToken().then((value) {
print("fcm token >>> " + value);
});
}
static void display(RemoteMessage message) async {
AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
//'This channel is used for important notifications.', // description
importance: Importance.high,
playSound: true);
try {
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final NotificationDetails notificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
//channel.description,
color: Colors.blue,
playSound: true,
icon: '#mipmap/ic_launcher',
));
await _notificationsPlugin.show(
id,
message.notification.title,
message.notification.body,
notificationDetails,
payload: message.data["route"],
);
} on Exception catch (e) {
debugPrint(e.toString());
}
}
static onForeground() {
Map notificationData;
FirebaseMessaging.onMessage.listen((message) {
// LocalNotificationService.initializeFCM(userId);
if (message.notification != null) {
notificationData = {
"title": message.notification.title,
"body": message.notification.body
};
}
LocalNotificationService.display(message);
});
return notificationData;
}
static onTerminated() {
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
final routeFromMessage = message.data["route"];
debugPrint('Route called for terminated state***************');
String userId = SharedUtils.getString('UserId');
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext)
.push(Routes.generateRoute(routeFromMessage));
}
}
});
}
static onMessageOpened() {
FirebaseMessaging.onMessageOpenedApp.listen((message) {
final routeFromMessage = message.data["route"];
print('Route called for background***************');
String userId = SharedUtils.getString('UserId');
Map notificationData = {
"title": message.notification.title,
"body": message.notification.body
};
if (userId.isEmpty && userId == "") {
SharedUtils.setString('route', routeFromMessage);
Navigator.push(Utils.navigatorKey.currentContext,
MaterialPageRoute(builder: (context) => LoginView()));
} else {
Navigator.of(Utils.navigatorKey.currentContext, rootNavigator: true)
.push(Routes.generateRoute(routeFromMessage));
}
return notificationData;
});
}
}

Flutter firebase_messaging - flutter_local_notifications

when the app is opened (foreground) and I receive a notification I want to navigate to a screen. The other 2 cases are working fine (background & terminated). I'm using this example
https://pub.dev/packages/firebase_messaging/example
help please I'm stuck in this for 2 days now. I know that I should add payload on onMessage.listen ok but after I did this?!!
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
/// Create a [AndroidNotificationChannel] for heads up notifications
AndroidNotificationChannel channel;
/// Initialize the [FlutterLocalNotificationsPlugin] package.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.instance.getToken().then((value) {
firebaseToken = value;
print('firebaseToken $firebaseToken');
});
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
runApp(MyApp());
}
'my home state'
int _messageCount = 0;
String constructFCMPayload(String token) {
_messageCount++;
return jsonEncode({
'token': token,
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'via': 'FlutterFire Cloud Messaging!!!',
'count': _messageCount.toString(),
},
'notification': {
'title': 'Hello FlutterFire!',
'body': 'This notification (#$_messageCount) was created via FCM!',
},
});
}
#override
void initState() {
super.initState();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
print(message.data);
print('onMessage method');
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: 'launcher_icon',
),
),
);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
print('A new onMessageOpenedApp event was published!');
print(message.data);
print('onMessageOpenedApp method');
if (loginState && message != null) {
if (message.data['module'] == 'article') {
articleID = await message.data['id'];
Navigator.pushNamed(context, 'ArticleDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'question') {
questionID = await message.data['id'];
Navigator.pushNamed(context, 'QuestionDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'reservation') {
Navigator.pushNamed(context, 'Reservations',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'job') {
Navigator.pushNamed(context, 'Jobs',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'addresses') {
Navigator.pushNamed(context, 'InterestedAddresses',
arguments: MessageArguments(message, true));
}
} else {
Splash();
}
});
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) async {
if (loginState && message != null) {
if (message.data['module'] == 'article') {
articleID = await message.data['id'];
Navigator.pushNamed(context, 'ArticleDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'question') {
questionID = await message.data['id'];
Navigator.pushNamed(context, 'QuestionDetails',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'reservation') {
Navigator.pushNamed(context, 'Reservations',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'job') {
Navigator.pushNamed(context, 'Jobs',
arguments: MessageArguments(message, true));
} else if (message.data['module'] == 'addresses') {
Navigator.pushNamed(context, 'InterestedAddresses',
arguments: MessageArguments(message, true));
}
} else {
Splash();
}
});
}
When you display local notification from FCM message in Android, you have to configure a function that will handle this case: received message is tapped while Android app is in foreground.
So add this configuration where you initalize local notifications:
await _flutterLocalNotificationsPlugin!.initialize(
const InitializationSettings(
android: AndroidInitializationSettings(),
iOS: IOSInitializationSettings()),
onSelectNotification: _onSelectNotification);
And the function should look something like this:
Future<dynamic> _onSelectNotification(String? payload) async {
}
You can try to add you navigation inside onSelectNotification callback, which you can add on notification initialization
Like this:
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (){
// Set your navigation code here!!
},
);

The class 'FirebaseMessaging' doesn't have a default constructor Flutter 2

Before switching to Flutter 2, I was using an old version of firebaseMessaging without problems, and now I have the latest version.After upgrading I get the following error:
The class 'FirebaseMessaging' doesn't have a default constructor.
And:
The method 'configure' isn't defined for the type 'FirebaseMessaging'.
Full class:
class ShowNotifications {
static final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();
static void initialization(){
var initializationSettingsAndroid =
new AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
static void showNotification(String title, String body) async {
await _demoNotification(title, body);
}
static Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_ID', 'channel name', 'channel description',
importance: Importance.max,
playSound: true,
// sound: 'sound',
// sound: true,
showProgress: true,
priority: Priority.high,
ticker: 'test ticker');
var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}
static Future onSelectNotification(String payload) async {
showDialog(
// context: context,
builder: (_) {
return new AlertDialog(
title: Text("PayLoad"),
content: Text("Payload : $payload"),
);
},
);
}
static notification(){
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
showNotification(message['notification']['title'], message['notification']['body']);
// print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
}
}
I was able to control this class from all the application pages.
What do I need to change with the new version. So that I can use the class as it was in the past.
Try to update your firebase_messaging package and also take care to use compatile packages for the other Firebase SDKs. I would recommend to copy the ones from the official documentation for each one you use.
Here is a full example how the new Firebase Messaging SDK would work with the new API:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../constants.dart';
FirebaseMessaging messaging = FirebaseMessaging.instance;
final _database = FirebaseDatabase.instance;
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
class MessagingService {
static bool showToast = true;
static String currentToken;
static void initialize() async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
if (showToast && message.notification != null) {
Fluttertoast.showToast(
msg: "${message.notification.title}: ${message.notification.body} ",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
//backgroundColor: Colors.red,
//textColor: Colors.white,
fontSize: 16.0,
);
}
});
messaging.onTokenRefresh.listen((String token) async {
await syncToken();
});
await syncToken();
}
static Future<String> getToken() async {
String token = await messaging.getToken();
return token;
}
static Future syncToken() async {
try {
String token = await messaging.getToken();
if (token != currentToken) {
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child(
'$kNotificationTokensSyncBasePath${_auth.currentUser.uid}/$token')
.set(true);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': true}, SetOptions(merge: true));
}
currentToken = token;
}
} catch (e) {
print(e);
}
return;
}
static Future unsyncToken(User user) async {
try {
String token = await messaging.getToken();
if (syncDatabase == databases.RealtimeDatabase) {
await _database
.reference()
.child('$kNotificationTokensSyncBasePath${user.uid}/$token')
.set(null);
} else {
await _firestore
.doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
.set({'$token': FieldValue.delete()}, SetOptions(merge: true));
}
currentToken = null;
} catch (e) {
print(e);
}
return;
}
}