Search code examples
flutterdartpush-notificationfirebase-cloud-messaging

Flutter FirebaseMessaging. Error sending notification: type 'Null' is not a subtype of type 'Object' in type cast



Future<void> sendNotificationToUser(String friendUid, String? title, String? body) async {
  try {
    DocumentSnapshot friendSnapshot = await FirebaseFirestore.instance.collection('users').doc(friendUid).get();
    String? friendFcmToken = await friendSnapshot['token_push'];
    print("friendFcmToken $friendFcmToken");

    await _firebaseMessaging.requestPermission();
    final String? fcmToken = await _firebaseMessaging.getToken();
    
    if (friendFcmToken != null) {
      await _firebaseMessaging.sendMessage(
        to: friendFcmToken,
        data: {
          'title': title!,
          'body': body!,
        },
      );
      print('Notification sent successfully');
    } else {
      print('Friend user does not have an FCM token');
    }
  } catch (e) {
    print('Error sending notification: $e');
  }
}

Hello, i'm working with FirebaseMessaging for the first time, and I encountered a problem.

enter image description here

Please help me figure out what the problem is.

I send notifications in chat.


Solution

  •  data: {
          'title': title ?? '',
          'body': body ?? '',
        },