Send notification over device using FCM and Flutter - flutter

currently I am trying to send a notification to multiple device. I already read the documentation on how to send notification to device group , they mentioned that I need to use registration_ids: [...] instead of to: token. And I also read somewhere that they mentioned about notification_key which is it will enabled to send the notification to the other device. So, I'm stuck on finding the key. But then, after few days browsing, I found out that here stated that the notification_key already deprecated. So, I would like to ask if any of you guys know how to send notification to multiple device without using console.
This I my code segment to send push the notification:
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
// Uri.parse('https://fcm.googleapis.com/fcm/notification'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'key=$serverKey',
'project_id':'....',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body2',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action':
'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'registration_ids': ['fbN9aYoORhihksrTo7j5D2:APA91b......', 'fArqpgKrTJ0fL8SUKddy2F:APA91bFWf1cnVMS8.......'],
// 'to': _token,
},
),
);
} catch (e) {
print("error push notification");
}
It work fine if I used to instead of registration_ids, but the things is as I understand is to is used if I want to send notification only for one device.
I already stuck with this issue for three days and still not found any solution. Most of them are using console instead. Your help will really made my day. Thank you in advance!

I found a solution and its work!
var serverKey =
'AAAAUb...';
QuerySnapshot ref =
await FirebaseFirestore.instance.collection('users').get();
try {
ref.docs.forEach((snapshot) async {
http.Response response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverKey',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': snapshot.data() ['tokenID'],
},
),
);
});
} catch (e) {
print("error push notification");
}

Related

non-local notification using workManager flutter

i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id = 7
await sFunction(id, await returnUserName());
}
return Future.value(true);
});
}
sFunction
sFunction(int id, String sender) async {
List<Map> response =
await SQLdb().readData('''SELECT * FROM `timer_chat` WHERE id = $id
''');
String reciever = response[0]['reciever'];
String message = response[0]['message'];
try {
String currentToken = await auth.getusertoken(reciever);
auth.sendnotify("my app",
"your message has been sent: " + message, "1", currentToken);
} catch (e) {
print("notification did not send: " + e.toString());
}
}
finally sendnotify
sendnotify(String title, String body, String id, String token) async {
try {
await http.post(
Uri.parse("https://fcm.googleapis.com/fcm/send"),
headers: <String, String>{
'content-type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': "FLUTTER_NOTIFICATION_CLICK",
'id': id.toString(),
"name": "me",
"lastname": "wolf"
},
"to": token
},
),
);
} catch (e) {
print("something went wrong in notiiiii" + e.toString());
}
}
i'm sending notifications using firebase cloud messaging API. it worked fine inside the app but in workManager it does not. any idea why?
thank you

How to send a user to a specific page via firebase notification when the app is terminated in flutter?

Main Screen
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(info: payload.toString())));
} else {}
} catch (e) {}
return;
});
void sendPushMessage(String token, String body, String title) async {
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=thekey'
},
body: jsonEncode(<String, dynamic>{
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'status': 'done',
'body': body,
'title': title
},
"notification": <String, dynamic>{
"title": title,
"body": body,
"android_channel_id": "androidchannelid"
},
"to": token,
}),
);
} catch (e) {
if (kDebugMode) {
print('error push notifications');
}
}
}
When the notification is received it should be send to the new screen and not the main screen.
This code works when the app is in background or foreground but it is not working when the app is terminated.
What should i do?
Use to getInitialMessage to check if there is a message when a application is opened.
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
// TODO navigate to a specific page
}
See Handling Interaction for details.

i want to send notification when receive a meesage in my chat app but it didn't work

i tried method using firebase_messaging: 7.0.1 but now its firebase_messaging: 14.0.2.
i got this error :
Converting object to an encodable object failed: Instance of 'Future<String?>'
sendNotif(String? title, String? body, String? id) async {
try {
await http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': id.toString(),
},
'to': FirebaseMessaging.instance.getToken(),
},
),
)
.then((value) => (value) {
print("send succeffuly");
});
} catch (e) {
print("THe ERROR : $e");
}
}
As the error message says, FirebaseMessaging.instance.getToken() returns a Future<String>, while the post API expects only current (non-Future) values.
The simplest fix is to await the value:
'to': await FirebaseMessaging.instance.getToken(),

how can get paylod data when I using FCM in flutter?

how can get paylod data when I using FCM in flutter?
I tried used this methods, but I still could not got the data...
where has issues?
void getInitialMessage() async {
RemoteMessage? message =
await FirebaseMessaging.instance.getInitialMessage();
print(message?.data["type"]);
if (message != null) {
if (message.data["type"] == "noti") {
print("AAAAA");
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
PostDetailScreen(postid: message.data["postid"]),
),
);
} else if (message.data["type"] == "active") {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PostDetailScreen(postid: '456'),
),
);
}
}
}
When I go to postman to test, I will send this format
Future<void> sendPushMessage(String token, String body, String title,
String postid, String images) async {
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=AAAAm2nkpqg:APA91bH9l8kYkJqGyGnVJhUe4dmG5KeYVrErEB_vl7vhZDGBAgFGOYsyHguDna-SBeP8juVoTtLQ61aI61QZ-46JFwaR-8KPai7CT6n4-jRZFBIMOHEl1Ph',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{'body': body, 'title': title},
'priority': 'high',
'timeToLive': 24 * 60 * 60,
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
'type': 'noti',
'postid': 'Mi6Y3sE9E0uz4uAvQjwC'
},
"to": token,
},
),
);
} catch (e) {
print("error push notification");
}
}
I can receive the Notification, but I have setting "type": "noti". So when I click the notification message, it shoule be print AAAAA and Navigator to PostDetailScreen. But It's always open app then go to homepage....
Send out FCM message with this structure, here I use NodeJS Firebase Cloud Function, but the important thing is to add the second, options part:
await admin.messaging().sendToDevice(tokens, {
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
type: 'noti',
postid: 'ulEdnFiEZxyyc33UNvJs'
},
notification: {
title: 'title',
body: 'body'
},
}, {
contentAvailable: true,
priority: 'high',
timeToLive: 24 * 60 * 60, // in seconds
});
After this, in getInitialMessage you should have:
message.data['type'] // 'noti'
message.data['postid'] // 'ulEdnFiEZxyyc33UNvJs'

Flutter: http.post the object

I am trying to send a http.post request with multiple variables.
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
When I remove acc: acc, Flutter sends requests. However, I need to send var acc value to the server in order to post it. I tried to encode it to JSON the http.post() function. It seems not working. How can I send the object as part of the post request?
This will work.
import 'dart:convert';
//....
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc.toString(),
},
),
);