Flutter Firebase Notification on Web - flutter

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())!;
}

Related

flutter_local_notification IOSNotificationDetails and DarwinNotificationDetails both not working

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()

flutter web not working due to await statement

I am having issues with Flutter web when I use await statement,
void main() async {
//debugPaintSizeEnabled = true;
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
this will not display anything on the browser and throws and error:
ChromeProxyService: Failed to evaluate expression 'title': InternalError: Expression evaluation in async frames is not supported. No frame with index 39..
I am stuck :(
debugging testing nothing worked
Run flutter channel stable followed by flutter upgrade --force
When using Firebase, you need to initalize it with options for the specific platform that you are using. Here goes and example on how to configure it for Flutter Web:
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
void main() async {
//debugPaintSizeEnabled = true;
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options = FirebaseOptions(
apiKey: 'YOUR API KEY',
appId: 'YOUR APP ID',
messagingSenderId: 'YOUR MESSAGING SENDER ID',
projectId: 'YOUR PROJECT NAME',
authDomain: 'YOUR AUTH DOMAIN (IF YOU HAVE)',
databaseURL: 'YOUR DATABASE URL (IF YOU USE FIREBASEDATABASE)',
storageBucket: 'YOUR STORAGE BUCKET',
)
);
runApp(MyApp());
}
All this information is available on your Firebase Project Console, just search for it. Hope it helps!

Flutter terminated notification is not working

first time when i run my app and terminate it, my terminated notifications work good, but if i run it again and terminate, i got this error in my run terminal,
and my notification is not received. Is it flutter issue.
is this a flutter error or my api error?
Here is my terminated notification code
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await Permission.notification.request();
await Permission.camera.request();
await Permission.microphone.request();
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
await _messaging.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
I tried to reboot my computer, and restart my androidStudio, but it does not help.

Firebase Cloud Messaging (Flutter): Error message when subscribing to topic

I have included Firebase Messaging in my app and I am getting the following error when I try to subscribe to topics.
FLTFirebaseMessaging: An error occurred while calling method Messaging#subscribeToTopic, errorOrNil => {
NSLocalizedFailureReason = "Invalid registration response :'Error=INVALID_PARAMETERS'. It is missing 'token' field.";
}
flutter: subscription error: [firebase_messaging/unknown] An unknown error has occurred.
As you can see it simply says "An unknown error has occurred", which is not very helpful to me.
Here is my code which is meant to obtain permissions for push notifications, then gets the token and subscribes to a list of topics...
Future<void> requestMessagingPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted notifiactions permission');
messaging.getToken().then((token) async {
print('Messaging token: $token');
//configure notification topics
//gets a list of strings (topic names) from provider and loops through them to subscribe to them all
GlobalProvider provider = context.read<GlobalProvider>();
if (provider.notificationTopicsSet == false) {
//subscribe to topics
for (var topic in provider.notificationTopics) {
print('topic subscribing... $topic');
try {
await messaging.subscribeToTopic(topic).then((value) => print('topic subscribed: $topic'));
} catch (e) {
print('subscription error: $e');
}
}
}
});
}
}
I am getting the same error in the console for every topic that is being looped through and subscribed to. The weird thing is that push notifications were working before, but now they don't seem to be.
I have tried updating Flutter to the latest version (3.3.7), I have tried updating both the Firebase Core package (2.1.1) and the Firebase messaging package to their latest versions (14.0.4) and I am still getting the error.
From pubspec.yaml:
firebase_core: ^2.1.1
firebase_messaging: ^14.0.4
What is this token that is missing? The subscribeToTopic() function only seems to take the topic name string. Am I missing something?
Thank you, any help will be greatly appreciated.
This ended up being only an issue with the iOS simulator. The error did not occur with the Android emulator and push notifications work fine on physical devices.

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.