flutter_local_notification IOSNotificationDetails and DarwinNotificationDetails both not working - flutter

I'm pretty new to learn flutter and I'm trying to push notification through flutter_local_notifications and firebase_messaging.
My flutter version is 3.3.9
Here's other pub version:
firebase_core: ^2.4.0
flutter_local_notifications: ^12.0.4
firebase_messaging: ^14.1.4
http: ^0.13.4
cloud_firestore: ^4.2.0
I've searched that if using flutter_local_notifications version 10 or above, should use DarwinNotificationDetails instead of IOSNotificationDetails. However both of them are NOT working in my case. All relative codes are below.
import flutter_local_notification:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
declare it:
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
If I'm using DarwinNotificationDetails, vscode will show error like this:
The name 'DarwinNotificationDetails' isn't a class.
Try correcting the name to match an existing class.
DarwinNotificationDetails error
If I'm using IOSNotificationDetails, it will show error like below when I try to launch device without debugging.
IOSNotificationDetails error
I've try to run flutter clean and delete pubspec.lock then reinstall all pub but not working. Also try to clean boot or wipe data to android device and still not working.
Please kindly help to let flutter_local_notification working normally.
Thanks a lot.
full code:
final android = AndroidInitializationSettings('#mipmap/ic_launcher');
final ios = DarwinInitializationSettings(); // get error here
final initSettings = InitializationSettings(android: android, iOS: ios);
flutterLocalNotificationsPlugin.initialize(
initSettings,
);
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
print('......message: ${message.notification?.title}--${message.notification?.body}');
BigTextStyleInformation bigTextStyleInformation = BigTextStyleInformation(
message.notification!.body.toString(),
htmlFormatBigText: true,
contentTitle: message.notification!.title.toString(),
htmlFormatContentTitle: true,
);
AndroidNotificationDetails androidPlatformChannelSpecitics = AndroidNotificationDetails(
'dbfood',
'dbfood',
importance: Importance.high,
styleInformation: bigTextStyleInformation,
priority: Priority.high,
playSound: true,
);
NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecitics,
iOS: DarwinNotificationDetails(), // also get error here
);
await flutterLocalNotificationsPlugin.show(
0,
message.notification?.title,
message.notification?.body,
platformChannelSpecifics,
payload: message.data['body'],
);
});

Const variables must be initialized with a constant value.
Try changing the initializer to be a constant expression.
You have to declare it as static const rather than just const . static , final , and const mean entirely distinct things in Dart: static means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members
add static keyword before const :
static const DarwinNotificationDetails()

Related

Flutter Firebase Notification on Web

In my flutter project, I already have notifications set up using firebase_messaging for Android and iOS. I am trying to add the same for Web. I had tried it before (mostly changing index.html with firebase-configs and initializing), but it had not worked then and I had left it. Now their document asks to use the new way, which asks only to configure it in the dart-files, and talks nothing about doing anything on index or other js files. So I have removed imports, and initialization from index.html, and not added any other file ( I have tried adding empty firebase-messaging-sw.js and removing it). This is the error I am getting:
[firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:44055/firebase-cloud-messaging-push-scope') with script ('http://localhost:44055/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. .
What am I missing? Are those steps incomplete? I also tried the steps in this article , but still have the same issues.
Edit
These are all the code-parts related to firebase-messaging.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
firebaseAnalytics = FirebaseAnalytics.instance;
firebaseMessaging = FirebaseMessaging.instance; //
final notificationSettings = await firebaseMessaging.requestPermission();
debugPrint('User granted permission: ${notificationSettings.authorizationStatus}');
if (!kIsWeb) {
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'This channel is used for important notifications.',
// description
importance: Importance.max,
);
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);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
.
.
.
.
.
.
.
.
if (kIsWeb) {
// this is where the code throws error:
token = (await firebaseMessaging.getToken(
vapidKey: "BLn....pH8",
))!;
} else {
token = (await firebaseMessaging.getToken())!;
}

How do I show a notification when app is closed?

I saw different question regarding this topic like this one:
Flutter send local notification when app is closed (alarm)
Some of them with accepted answers but nothing seems to work with latest version. Notification package has changed and all of these examples are deprecated.
I tried actual version (flutter_local_notifications: ^12.0.0) and as soon as I close the app I don't receive any notification at all.
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.high,
);
var detroit = tz.getLocation('America/Detroit');
var now = tz.TZDateTime.now(detroit);
await _flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(now.location).add(const Duration(seconds: 5)),
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
The only notifications that I implemented in the background are the ones coming from firebase cloud functions, but I don't want to rely on this for simple notifications (specially because of the plan).
Is there anything working out there?
This was already working. The trick was to not test on debug:
flutter run --release

Flutter StreamChat SDK : Notifications not showing when the app is closed?

I'm working on a flutter delivery app and I want to integrate chat functionality and I found out that the StreamChat SDK is the best solution for that !
I already integrated the SDK and it's working , so to receive a notification when there is a new message I set up push notifications according to the docs in my flutter applications, when I test it up using stream CLI ,
I receive the notification and it also works when the app on the background but I don't receive anything when the app is closed and also nothing shows on the dashboard logs !
=====My code ========
await client.connectUser(
User(
id: sharedPreferences.getString('username'),
),
token,
);
var fcm = await FirebaseMessaging.instance.getToken();
await client.addDevice(fcm, PushProvider.firebase);
final channel = client.channel(
'messaging',
id: deliveryData['deliveryNumber'],
extraData: {
"name": deliveryData['title'],
},
);
final currentUserId = client.state.user.id;
client
.on(
EventType.messageNew,
EventType.notificationMessageNew,
)
.listen((event) async {
if (event.message?.user?.id == currentUserId) {
return;
}
final flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final initializationSettingsAndroid =
AndroidInitializationSettings('launch_background');
final initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin
.initialize(initializationSettings);
await flutterLocalNotificationsPlugin.show(
event.message.id.hashCode,
'New message from : ' + event.message.user.name,
event.message.text,
NotificationDetails(
android: AndroidNotificationDetails(
'message channel',
'Message channel',
'Channel used for showing messages',
icon: '#drawable/notification',
priority: Priority.high,
importance: Importance.high,
),
),
);
});
I found the solution for that , the problem was that I used channel.watch(); instead, I should also add the user to the channel
channel.addMembers(["thierry", "josh"]); in order to receive push notifications as it is mentioned in the docs
Watchers vs Members
The concepts of watchers vs members can require a bit of clarification:
members: a permanent association between a user and a channel. If the
user is online and not watching the channel they will receive a
notification event, if they are offline they will receive a push
notification.
watchers: the list of watchers is temporary. It's anyone who is
currently watching the channel.
Being able to send messages, and otherwise engage with a channel as a non-member requires certain permissions. For example, we have pre-configured permissions on our livestream channel type to allow non-members to interact, but in the messaging channel type, only members of the channel can interact.

Flutter Notifications after one hour

Hello I need to make local notification on mobile whenever a button is pressed. And i don't want to make the notification instantly but after one hour when the user hit that button does anyone have any idea?
I tried this plugin flutter_local_notifications: ^8.2.0
But can some help me how to do the trigger after one hour
Thanks
Use this function to call notifications every hour
shownotifications() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('repeating channel id',
'repeating channel name', 'repeating description');
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await FlutterLocalNotificationsPlugin().periodicallyShow(0, 'Test title',
'test body', RepeatInterval.hourly, platformChannelSpecifics,
androidAllowWhileIdle: true);
}
and follow this article step by step to to setup the package you are using

FCM : Cant get a pop up notification when app is running in background

I am using "Firebase Cloud Messaging" for receiving notifications and "flutter_local_notifications" plugin to configure and display them on my device. So my current scenario is when my app is running (in foreground), I am receiving proper notification as expected (a pop-up plus it gets stored in system-tray) like this :
It also gets stored in the system tray as expected.
But when I keep the app in background and post a notification request ........ It just stores the notification in the tray but doesnt show a pop-up notification. Like this :
As seen in the image above .... it just stores the notification in the image tray but doesn't show pop-up notification like when the app is running in foreground.
I thought I was an issue in the "backgroundMessage" Callback but what I observed was whenever I posted a notification when the app is in background, instead of executing the "backgroundMessage" callback it always gave this exception :
W/FirebaseMessaging(22744): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
Below is the code where I configured the FirebaseMessaging instance :
_firebaseMessaging.configure(
onMessage: notification,
onBackgroundMessage: notificationBack,
);
'notification' Callback :
Future<dynamic> notification(Map<String,dynamic> message) async {
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'Channel ID', 'Channel title', 'channel body',
priority: Priority.High,
importance: Importance.Max,
ticker: 'test');
IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
NotificationDetails notificationDetails =
NotificationDetails(androidNotificationDetails, iosNotificationDetails);
await _flutterLocalNotificationsPlugin.show(
0, 'Notification', 'New Notification', notificationDetails);
}
'notificationBack' callback :
static Future<dynamic> notificationBack(Map<String,dynamic> message) async {
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'Channel ID', 'Channel title', 'channel body',
priority: Priority.High,
importance: Importance.Max,
visibility: NotificationVisibility.Public,
ticker: 'test');
IOSNotificationDetails iosNotificationDetails = IOSNotificationDetails();
NotificationDetails notificationDetails =
NotificationDetails(androidNotificationDetails, iosNotificationDetails);
await _flutterLocalNotificationsPluginBack.show(
0, 'Hello there', 'please subscribe my channel', notificationDetails);
}
AndroidManifest.xml :
Sorry for the screenshot instead of text format .... but I dont know why all these terms were highlighted in red saying "Cant resolve symbol ...." and "Unresolved package 'flutterlocalnotifications'" in case of reciever of flutterlocalnotification.
My main goal is to get the game pop-up notification and one in the system tray even when the app is in background. (Just how it displayed when it was in foreground).
I know the question is a bit long but I had to provide all my observation about the issue so please bare with it :)
Thankyou in advance for the help.