Issue
I am actually working with a e-commerce app and want to send notification to a delivery boy when order is placed from user app.
How can we identify the specific delivery boy app from backgroud (when app is exited).
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage
message) async {
await Firebase.initializeApp();
SharedPreferences _prefs = await SharedPreferences.getInstance();
print('A message just showed : ${message.messageId}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// <------------Local Notification Initilization-------------->
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
runApp(MyApp());
}
Solution
Use http request to send notifications, and use topic parameter for specific user selection, check the code example that I’ve used in my case:
final String serverToken = 'YOUR_SERVER_TOKEN_HERE';
FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
Future<Map<String, dynamic>> sendAndRetrieveMessage(String typeOfNotification,
{String? sellerId, String? chatId, String? postId}) async {
NotificationSettings settings = await firebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
String notification = getNotificationMessage(typeOfNotification);
notificationMsg.value = notification;
addToNotifications(sellerId!, notification, postId ?? "$userId", chatId ?? "$userId");
print('User granted permission: ${settings.authorizationStatus}');
String topic = '';
if (typeOfNotification == 'live') {
topic = "/topics/$userId";
} else if (typeOfNotification == 'post') {
topic = "/topics/$userId";
} else {
topic = "/topics/${sellerId}_personal";
}
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': "${userIsASeller.value ? shopName.value : userName.value} $notification",
'title': "Shopenlive",
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
'title': "Shopenlive",
'body': "${userIsASeller.value ? shopName.value : userName.value} $notification",
},
'to': topic,
},
),
);
final Completer<Map<String, dynamic>> completer = Completer<Map<String, dynamic>>();
/* firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
completer.complete(message);
},
); */
return completer.future;
}
Answered By – Akhlaq Shah
Answer Checked By – Pedro (FlutterFixes Volunteer)