flutter_local_notifications does not show the notification(IOS only) - ios

i am beginner in flutter. I try to make an app which should notify users on scheduled time. I decided to use flutter_local_notification.
(I am trying to implement this only IOS as first step so that is why code blocks related with android commented in.)
class NotificationHelper {
FlutterLocalNotificationsPlugin
flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
initializeNotification() async {
//tz.initializeTimeZones();
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
onDidReceiveLocalNotification: onDidReceiveLocalNotification
);
// final Android InitializationSettings initializationSettingsAndroid =
// Android InitializationSettings("appicon");
final InitializationSettings initializationSettings =
InitializationSettings(
iOS: initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: selectNotification);
}
onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) async {
// display a dialog with the notification details, tap ok to go to another page
// showDialog(
// //context: context,
// builder: (BuildContext context) => CupertinoAlertDialog(
// title: Text(title),
// content: Text(body),
// actions: [
// CupertinoDialogAction(
// isDefaultAction: true,
// child: Text('Ok'),
// onPressed: () async {
// Navigator.of(context, rootNavigator: true).pop();
// await Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => SecondScreen(payload),
// ),
// );
// },
// )
// ],
// ),
// );
}
Future selectNotification(String? payload) async {
if (payload != null) {
print('notification payload: $payload');
} else {
print("Notification Done");
}
}
void requestIOSPermissions() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
displayNotification({required String title, required String body}) async {
print("doing test");
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your channel id', 'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
flutterLocalNotificationsPlugin.show(
12345,
"A Notification From My Application",
"This notification was sent using Flutter Local Notifcations Package",
platformChannelSpecifics,
payload: 'data');
}
}
and i call the initializeNotification() function on my main.dart like this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
NotificationHelper().requestIOSPermissions();
NotificationHelper().initializeNotification();
runApp(const MyApp());
}
and after user logged in,
I just try to see my notification so i call displayNotification() on a button like this:
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
NotificationHelper().displayNotification(title: 'title', body: 'hede');
},
color: Colors.white,
iconSize: 25,
),
and also i call this code in AppDelegate.swift
import UIKit
import Flutter
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
when application opens it successfully asks permissions for send notifications. After it allowed i just try to call displayNotification() but it doesn't work. I cannot see any notification on my simulator.
environment:
sdk: ">=2.15.1 <3.0.0"
flutter_local_notifications: ^9.3.3
What should i do ? Thank you for you all your answers.

I think notifications doesn't work currently on İOS simulator. You should try real ios device

Related

Custom iOS notifications sound local notifications package Flutter

I'm using Firebase Cloud Messaging to send notifications to my flutter app, and I'm using the flutter_local_notifications package to handle them, but when I tried to change the default notification sound it worked for android but didn't work for iOS, keep in mind that I add the "sound.aiff" to the root of the native iOS project, can anyone show me what I'm missing here, and thanks in advance
class FCMFunctions {
static final FCMFunctions _singleton = new FCMFunctions._internal();
FCMFunctions._internal();
factory FCMFunctions() {
return _singleton;
}
late FirebaseMessaging messaging;
//************************************************************************************************************ */
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;
/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
//************************************************************************************************************ */
Future initApp() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
messaging = FirebaseMessaging.instance;
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
sound: RawResourceAndroidNotificationSound('sound'),
playSound: true,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
//for IOS Foreground Notification
await messaging.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void initializeNotifications() async {
var initializationSettingsAndroid =
const AndroidInitializationSettings('icon');
var initializationSettingsIOS = const IOSInitializationSettings();
//var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
}
Future onSelectNotification(String? payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
}
navigatorKey.currentState!.pushNamed(Routes.blackCurrency,
arguments: false); //message.data['category']
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Future subscripeToTopics(String topic) async {
await messaging.subscribeToTopic(topic);
}
///Expire : https://firebase.google.com/docs/cloud-messaging/manage-tokens
Future<String?> getFCMToken() async {
final fcmToken = await messaging.getToken();
return fcmToken;
}
void tokenListener() {
messaging.onTokenRefresh.listen((fcmToken) {
print("FCM Token dinlemede");
// TODO: If necessary send token to application server.
}).onError((err) {
print(err);
});
}
/// IOS
Future iosWebPermission() async {
if (Platform.isIOS || kIsWeb) {
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
}
}
///Foreground messages
///
///To handle messages while your application is in the foreground, listen to the onMessage stream.
void foreGroundMessageListener() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print(
'///////////////////////////// NOTIFICATIONS ARE COMMING /////////////////////////////');
print('${message.notification!.body} ');
print("Message data type : ${message.data.runtimeType}");
var bodyRaw = message.data['body'];
var body = List<dynamic>.from(jsonDecode(bodyRaw ?? '[]'));
print("body : $body");
String bodyMessage = '';
if (body.first['sale'] == null) {
bodyMessage = body.first['name'];
} else if (body.first['name'] == null) {
bodyMessage = body.first['sale'];
} else {
bodyMessage =
body.map((e) => e['name'] + '-' + e['sale']).join(', ').toString();
}
RemoteNotification? notification = RemoteNotification(
android: const AndroidNotification(
smallIcon: 'assets/imgs/logo.png',
priority: AndroidNotificationPriority.highPriority,
visibility: AndroidNotificationVisibility.public,
),
apple: const AppleNotification(
sound: AppleNotificationSound(
name: 'sound',
volume: 1.0,
),
),
title: message.data['title'],
body: bodyMessage,
);
// message.notification;
AndroidNotification? android =
notification.android; //message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
importance: Importance.max,
priority: Priority.max,
ticker: 'ticker',
sound: const RawResourceAndroidNotificationSound('sound'),
// icon: "#mipmap/icon",
playSound: true,
styleInformation: const DefaultStyleInformation(true, true),
),
iOS: const IOSNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
sound: 'sound',
),
),
);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('A new onMessageOpenedApp event was published!');
navigatorKey.currentState!.pushNamed(Routes.blackCurrency,
arguments: false); //message.data['category']
// Navigator.pushNamed(
// context,
// '/message',
// arguments: MessageArguments(message, true),
// );
});
}
}
final fcmFunctions = FCMFunctions();
Your server administrator will send you the sound name in notification payload which you added in iOS folder. Payload will look like this
{
aps =
{
alert = "notification message";
sound = "example.caf";
};
}
more information check this reference link
49
49
custom sound file for your app, follow this apple documentation.

How to get flutter local notification on iOS using only FCM data message?

I have an app that send notifications if someone commented or published a new post. I use FCM and flutter local notification. It works well on Android, but on iOS it does not. I realized if I add a 'notification' message block to the firebase function then finally I get the data message BUT I get the notification message too at the same time. That is not what I want. If I remove Notification message then data message not triggered and I do not get any notification.
The app should works only from iOS 10+. I tried this on iOS 15.
This is my firebase function:
exports.myFunction = functions.firestore
.document("animal/{message}")
.onCreate((snapshot, context) => {
return admin.messaging().sendToTopic("animal", {
data: {
latitude: snapshot.data()["latitude"].toString(),
longitude: snapshot.data()["longitude"].toString(),
title: snapshot.data().username,
body: snapshot.data().description,
uid: snapshot.data().userId,
animalId: snapshot.id,
},
//I do not want to use this, but if I remove this I do not get any push notification. Data notification neither.
//On Android it does not matter if I delete notification block or no. I will get the data notification.
notification: {
title: "title",
body: "new post",
},
});
});
In main.dart there is the flutter local notification initializing
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final AndroidInitializationSettings _initialzationSettingsAndriod =
AndroidInitializationSettings('noticon');
final IOSInitializationSettings _initialzationSettingsIOS =
IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
final InitializationSettings _initializationSettings = InitializationSettings(
android: _initialzationSettingsAndriod, iOS: _initialzationSettingsIOS);
_flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await _flutterLocalNotificationsPlugin.initialize(
_initializationSettings,
onSelectNotification: (payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
initPayload = payload!;
await navigatorKey.currentState!.push(CupertinoPageRoute<void>(
builder: (BuildContext context) => AnimalDetailScreen(payload, true),
));
},
);
....
#override
void initState() {
super.initState();
_requestPermissions();
final messaging = FirebaseMessaging.instance;
messaging.subscribeToTopic('animal');
messaging.subscribeToTopic('notifications');
messaging.requestPermission(
alert: true,
sound: true,
badge: true,
provisional: false,
);
And this is the showing notification. If I remove the notification message from firebase function then onMessage cannot be called on iOS but on only Android.
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
print("onMessage called");
....
if (isValid && currentUser != message.data['uid']) {
showNotification(message);
notifierCounter.value = notifierCounter.value + 1;
}
}
...
showNotification(RemoteMessage message) async {
Map<String, dynamic> data = message.data;
await flutterLocalNotificationsPlugin.show(
data.hashCode,
data['title'],
data['body'],
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
priority: Priority.high,
),
iOS: IOSNotificationDetails(),
),
payload: data['animalId'],
);
}
I found a solution.
I changed this:
notification: {
title: "title",
body: "new post",
},
to:
notification: {
sound: "default",
},
In this way I wont get automatic push notification and I can handle data message on iOS.

Flutter - How to remove iOS notification badge after opening app

When I send a notification from Firebase Cloud Messaging, the notification badge shows up on the app icon, but there is no code to remove it.
The count of notifications do not matter so I don't have to have any notification counter or whatever, so all I need to do is clear the notification badge when the app is opened.
How can I accomplish this without rewriting my entire code for notifications (I barely got it working)?
This is the code:
_fcm.getToken().then((token) {
print("The token is: " + token);
setState(() {
tokenSave = token;
});
});
_fcm.requestPermission(
sound: true,
badge: true,
alert: true,
provisional: false,
);
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,
channel.description,
color: Colors.blue,
playSound: true,
icon: null,
),
),
);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("onMessageOpenedApp event");
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text(notification.title),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(notification.body)],
),
),
);
});
}
});
}
Add the following function to your AppDelegate.swift, under the application() function:
override func applicationDidBecomeActive(_ application: UIApplication) {
application.applicationIconBadgeNumber = 0;
}
I've had the same problem before. My workaround was using the App badger package
With that package you can do the following in your main.dart or any other entrypoint of your application:
FlutterAppBadger.removeBadge();
or
FlutterAppBadger.updateBadgeCount(0);

Flutter App crash on IOS by using google_maps_flutter

I'm creating my first Flutter app. The app should show among other things on some places on a map. For the map I use google_maps_flutter (https://pub.dev/packages/google_maps_flutter).
Everything works fine on Android. As soon as I start the app on IOS and click on "Map" in my app, the app crashes without stacktrace. Android Studio just says "Lost connection to Device".
I have the SDK for Android and IOS active on the Google Cloud Platform and have added the key in the appDelegate.swift in my project.
I dont get it. Does anyone know what the problem could be? Thanks a lot for your help <3
This is my Class, which returns the Scaffold with Google Maps Widget:
class WaterMapScreen extends StatefulWidget {
#override
State<WaterMapScreen> createState() => _WaterMapScreenState();
}
class _WaterMapScreenState extends State<WaterMapScreen> {
GetIt getIt = GetIt.instance;
WaterService waterService;
List<Section> sectionList;
Location _location = new Location();
StreamController<FavSection> _streamController =
StreamController<FavSection>();
Set<Polygon> polygonSet = new Set();
UserService userService;
FavSection _selectedSection;
_WaterMapScreenState() {
waterService = getIt.get<WaterService>();
userService = getIt.get<UserService>();
}
initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_outlined, color: Colors.orange),
onPressed: () {
Navigator.pop(context);
}),
title: Text(
"Entdecken",
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.orange),
),
),
body: Stack(children: <Widget>[
getGoogleMapWithPolygons(),
CustomSlidingPanel(stream: _streamController.stream),
]),
);
}
FutureBuilder getGoogleMapWithPolygons() {
return FutureBuilder(
future: fetchSectionListWithFavorites(),
builder: (BuildContext context, AsyncSnapshot sectionListAsync) {
switch (sectionListAsync.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(color: Colors.orange));
default:
if (sectionListAsync.hasError) {
print('Error: ${sectionListAsync.error}');
return new Center(child: Text('Es ist ein Fehler aufgetreten'));
} else {
return FutureBuilder(
future: _location.getLocation(),
builder:
(BuildContext context, AsyncSnapshot locationAsync) {
switch (locationAsync.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(
color: Colors.orange));
default:
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(locationAsync.data.latitude,
locationAsync.data.longitude),
zoom: 10),
myLocationButtonEnabled: true,
mapType: MapType.normal,
myLocationEnabled: true,
polygons: sectionListAsync.data
.where((item) =>
item.section.gewaesserTyp == "SEE" ||
item.section.gewaesserTyp == "WEIER")
.map<Polygon>(
(item) => Polygon(
polygonId: PolygonId(item.section.id),
points: item.section.paths
.map<LatLng>((path) =>
LatLng(path.lat, path.lng))
.toList(),
fillColor: Colors.orange.withOpacity(0.5),
strokeColor: Colors.deepOrange,
strokeWidth: 5,
consumeTapEvents: true,
onTap: () {
_streamController
.add(_selectedSection = item);
},
),
)
.toSet(),
polylines: sectionListAsync.data
.where((item) =>
item.section.gewaesserTyp == "BACH" ||
item.section.gewaesserTyp == "FLUSS")
.map<Polyline>(
(item) => Polyline(
polylineId: PolylineId(item.section.id),
points: item.section.paths
.map<LatLng>((path) =>
LatLng(path.lat, path.lng))
.toList(),
color: Colors.deepOrange,
width: 5,
consumeTapEvents: true,
onTap: () {
_streamController
.add(_selectedSection = item);
},
),
)
.toSet(),
onTap: (LatLng latLng) {
_streamController.add(_selectedSection = null);
},
);
}
});
}
}
});
}
This is my appDelegate.swift:
import UIKit
import Flutter
import GoogleMaps
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("MyTopSecretApiKey")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
My pubspec.yaml:
name: fishr
description: Mobile Fishing Guide
version: 1.0.0+5
environment:
sdk: ">=2.2.2 <3.0.0"
dependencies:
shared_preferences: ^2.0.6
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
font_awesome_flutter: ^9.0.0
flutter_bloc: ^7.0.0
http: ^0.13.1
meta: ^1.1.6
equatable: ^2.0.0
get_it: ^7.1.3
google_maps_flutter: ^2.0.3
location: ^4.1.1
url_launcher: ^6.0.3
expansion_tile_card: ^2.0.0
settings_ui: ^1.0.0
simple_animations: ^3.1.1
popover: ^0.2.2
charts_flutter: ^0.10.0
syncfusion_flutter_charts: ^19.1.64
sliding_up_panel: ^2.0.0+1
flutter_speed_dial: ^3.0.5
flutter_native_splash: ^1.1.8+4
flutter_launcher_icons: ^0.9.0
lint: ^1.5.3
introduction_screen: ^2.1.0
buy_me_a_coffee_widget: ^2.0.0-nullsafety.0
material_floating_search_bar: ^0.3.4
dev_dependencies:
mockito: ^5.0.10
# test_coverage: ^0.4.2
bloc_test: ^8.0.0
flutter_test:
sdk: flutter
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
flutter_native_splash:
color: "#ffffff"
image: "assets/icon/splash_regular.png"
color_dark: "#262626"
image_dark: "assets/icon/splash_dark.png"
android: true
ios: true
flutter:
uses-material-design: true
assets:
- assets/images/
- assets/icon/
- assets/water/
It was an Permission Issue. Adding the following permissions in the ios/info.plist solved the problem :)
<!-- Permission options for the `location` group -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>Need location when in use</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Always and when in use!</string>
<key>NSLocationUsageDescription</key>
<string>Older devices need location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can I have location always?</string>
//Update your AppDelegate file as below
import UIKit
import Flutter
import GoogleMaps
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("YOUR MAP API KEY")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

Flutter ios device doesn't trigger onMessage from FCM notification. Sendtodevice fails when implementing APNs

In my fcm cloud function to send notifications to other players, it fails to send when I add the apns layer. When the apns layer is removed, notifications appear on android but for iOS the notifications are received in the front end but fail to trigger the onMessage function to display an alert dialog.
var payload = {
data: {
click_action: "FLUTTER_NOTIFICATION_CLICK",
notificationType: "friendsRequest",
fromUsername: fromUsername,
fromProfilePic: fromProfilePic,
fromColorIndex: fromColorIndex,
type: type
},
};
This payload returns a server response of "crash"
To enable notification for iOS you need to set up FCM for iOS first:
As you said you have generated APNs. just confirm have you linked apn with firebase project or not. after that open your project ios module in Xcode and make following changes in AppDelegate
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as?
UNUserNotificationCenterDelegate
}
Make changes in flutter side (I'm using this code in splash screen):
Initialization
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
Code in initState()
var initializationSettingsAndroid =
new AndroidInitializationSettings('#mipmap/ic_launcher'); //replace with your app icon file
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
FirebaseNotifications().setUpFirebase(_firebaseMessaging);
_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");
},
);
Methods for notification:
void showNotification(String title, String body) async {
await _demoNotification(title, body);
}
Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_ID', 'channel name', 'channel description',
importance: Importance.Max,
playSound: true,
sound: 'sound',
showProgress: true,
icon: 'notification_icon',
color: AppTheme.secondaryaccent,
priority: Priority.High,
ticker: 'test ticker');
var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}

Resources