firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.71k stars 3.97k forks source link

[firebase_messaging]: iOS FirebaseMessaging.instance.getInitialMessage return null when click on Notification in killed State. #12337

Closed himanshupapreja closed 8 months ago

himanshupapreja commented 8 months ago

Bug report

Describe the bug I send the notification from asp.net Core backend. On iOS When app is killed, Notification receive. When I click on notification, App open but no data is shown. I added log and Find that FirebaseMessaging.instance.getInitialMessage return null value.

Steps to reproduce

Steps to reproduce the behavior:

  1. Get the FCM token from the app
  2. Send a notification using the FCM token using the following payload:
var message = new MulticastMessage()
                        {
                            Tokens = registrationTokens,
                            Data = new Dictionary<string, string>()
                            {
                                { "body", rjsonPayload.body },
                                { "title", rjsonPayload.title },
                                { "sound", "default"},
                                { "notification", "ApprovalRequestRecieved" },
                                { "jsonData", jsonData },
                                { "silent", "true" },
                                { "UserId", authenticatorMethod.UserId.ToString() },
                                { "EmailId", authenticatorMethod.EmailId },
                                { "ApplicationName", authenticatorMethod.ApplicationName },
                                { "OrganizationId", authenticatorMethod.OrganizationId.ToString() },
                                { "OrganizationName", authenticatorMethod.OrganizationName },
                            },
                            Notification = new Notification
                            {
                                Body = rjsonPayload.body,
                                Title = rjsonPayload.title,
                            },
                            Android = new AndroidConfig
                            {
                                Priority = Priority.High
                            },
                            Apns = new ApnsConfig
                            {
                                Aps = new Aps
                                {
                                    AlertString = rjsonPayload.body,
                                    ContentAvailable = true
                                }
                            }
                        };
                        var result = await SendMulticastNotification(message, registrationTokens);
private async Task<List<string>> SendMulticastNotification(MulticastMessage message, List<string> androidTokens)
        {
            var failedTokens = new List<string>();
            try
            {
                var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
                if (response.FailureCount > 0)
                {
                    for (var i = 0; i < response.Responses.Count; i++)
                    {
                        if (!response.Responses[i].IsSuccess)
                        {
                            failedTokens.Add(androidTokens[i]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return failedTokens;
        }
  1. Receive Notification in iOS device when app is Killed.
  2. Click on Notification -> App open and Load Home page with default data. But No data is shown which is send in Notification

Expected behavior

FirebaseMessaging.instance.getInitialMessage()should return value when click on notification.

Sample project

import 'dart:async';

import 'package:alecomauthenticatorapp/Common/constants.dart';
import 'package:alecomauthenticatorapp/LocalDatabase/localStorage.dart';
import 'package:alecomauthenticatorapp/LocalDatabase/notificationDbService.dart';
import 'package:alecomauthenticatorapp/Localizations/appTranslations.dart';
import 'package:alecomauthenticatorapp/Models/serviceResponse.dart';
import 'package:alecomauthenticatorapp/Views/home.dart';
import 'package:alecomauthenticatorapp/Views/lockScreen.dart';
import 'package:alecomauthenticatorapp/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_lock/flutter_app_lock.dart';
import 'package:get/get.dart';
import 'package:alecomauthenticatorapp/Common/global.dart';
import 'package:alecomauthenticatorapp/LocalDatabase/accountListDbService.dart';

NotificationHelper notificationHelper = NotificationHelper();

@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
  if(kDebugMode) {
    print('Data come from Firebase background ${message.data['body']}');
    print('Data come from Firebase background 2${message.notification}');
  }
}
Future<void> main() async{
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent
      )
  );
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
  };
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

  FirebaseMessaging.instance.getInitialMessage().then((message) async{
    if (message != null) {
      NotificationModel notificationResponse = NotificationModel.fromJson(message.data);
      if (notificationResponse.notification == NotificationPageType.approvalRequestRecieved) {
        await NotificationDbService.addUpdateDataInDB(notificationResponse);
      }
    }
  });
  notificationHelper.initialize();

  FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(false);

  var isAppLock = await LocalStorage.getBool(LocalStorageStrings.appLock);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]).then((_)  async{
    runApp(
      AppLock(builder: (arg) {
        return const MyApp();
      },
        lockScreen: const LockScreen(),
        enabled: isAppLock,
        onBackPressed: (ctx) {
          SystemNavigator.pop(animated: true);
          AppLock.of(ctx as BuildContext)!.setEnabled(true);
        },
        backgroundLockLatency: const Duration(milliseconds: 10),
      ),
    );
    // runApp(const MyApp());
  });
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    setState(() {
      isAppOpen = true;
    });
    super.initState();
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      builder: (BuildContext context, Widget? child) => MediaQuery(
        data: MediaQuery.of(context).copyWith(
            textScaler: const TextScaler.linear(1)
        ),
        child: child!,
      ),
      translations: AppTranslations(),
      locale: const Locale(LocalStorageStrings.englishCode),
      theme: ThemeData().copyWith(
        colorScheme: ThemeData().colorScheme.copyWith(primary: ConstantColors.blackColor).copyWith(error: ConstantColors.redColor),
      ),
      debugShowCheckedModeBanner: false,
      initialRoute: 'home',
      routes: {
        'home': (context) => const HomePage(),
      },
    );
  }
}

class NotificationHelper{
  static StreamController<NotificationModel> controller = StreamController<NotificationModel>.broadcast();

  Future<void> initialize() async{
    // Receive Notification when app in open mode
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async{
      if(kDebugMode) {
        print('Data come from Firebase ${message.data['body']}');
      }

      NotificationModel notificationResponse = NotificationModel.fromJson(message.data);
      handleNotification(notificationResponse);
      // showNotification(message);
    });

    // App open from notification in background mode
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async{
      print('App Open From FirebaseMessaging.onMessageOpenedApp');
      NotificationModel notificationResponse = NotificationModel.fromJson(message.data);
      handleNotification(notificationResponse);
    });

    // When token refreshed
    FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) async{
      // TODO: If necessary send token to application server.
      await LocalStorage.setString(LocalStorageStrings.firebaseToken, fcmToken);
      AccountListDbService.getDataFromDB().then((accountList) {
        List<int> userIds = [];
        if(accountList.isNotEmpty) {
          for(final accountDetail in accountList) {
            if(accountDetail.userId != null && accountDetail.userId!.isGreaterThan(0)){
              userIds.add(accountDetail.userId!);
              Global.updateFirebaseTokenServer(accountDetail.userId!);
            }
          }
        }
        // Global.updateFirebaseTokenServer(userIds);
      });
    }).onError((err) { });
  }

  handleNotification(NotificationModel notificationResponse) async {
    NotificationHelper.controller.sink.add(notificationResponse);
  }
}

Additional context

I just need FirebaseMessaging.instance.getInitialMessage return value not


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.16.3, on macOS 14.2.1 23C71 darwin-arm64 (Rosetta), locale en-IN) [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 15.0.1) [✓] Chrome - develop for the web [✓] Android Studio (version 2022.3) [✓] Connected device (3 available) [✓] Network resources • No issues found! ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 3.2.3 Flutter SDK 3.16.3 alecomauthenticatorapp 1.0.1+1 dependencies: - awesome_dialog 3.1.0 [flutter rive] - cached_network_image 3.3.0 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image] - connectivity_plus 5.0.2 [flutter flutter_web_plugins connectivity_plus_platform_interface js meta nm] - cupertino_icons 1.0.6 - device_info_plus 9.1.1 [device_info_plus_platform_interface ffi file flutter flutter_web_plugins meta win32 win32_registry] - encrypt 5.0.3 [args asn1lib clock collection crypto pointycastle] - firebase_core 2.24.2 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_crashlytics 3.4.8 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace] - firebase_messaging 14.7.9 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - flutter 0.0.0 [characters collection material_color_utilities meta vector_math web sky_engine] - flutter_app_lock 3.0.0 [flutter] - flutter_html 3.0.0-beta.2 [html csslib collection list_counter flutter] - flutter_local_notifications 16.2.0 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone] - flutter_secure_storage 9.0.0 [flutter flutter_secure_storage_linux flutter_secure_storage_macos flutter_secure_storage_platform_interface flutter_secure_storage_web flutter_secure_storage_windows meta] - flutter_svg 2.0.9 [flutter vector_graphics vector_graphics_codec vector_graphics_compiler] - get 4.6.6 [flutter] - http 1.1.2 [async http_parser meta web] - intl 0.18.1 [clock meta path] - local_auth 2.1.7 [flutter local_auth_android local_auth_ios local_auth_platform_interface local_auth_windows] - local_auth_android 1.0.36 [flutter flutter_plugin_android_lifecycle intl local_auth_platform_interface] - local_auth_ios 1.1.5 [flutter intl local_auth_platform_interface] - mobile_scanner 3.5.5 [flutter flutter_web_plugins js] - package_info_plus 5.0.1 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface web win32] - path_provider 2.1.2 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows] - permission_handler 11.1.0 [flutter meta permission_handler_android permission_handler_apple permission_handler_html permission_handler_windows permission_handler_platform_interface] - pin_code_fields 8.0.1 [flutter] - qr_scanner_overlay 0.0.2 [flutter] - shared_preferences 2.2.2 [flutter shared_preferences_android shared_preferences_foundation shared_preferences_linux shared_preferences_platform_interface shared_preferences_web shared_preferences_windows] - upgrader 8.4.0 [flutter device_info_plus html http os_detect package_info_plus shared_preferences url_launcher version xml] - url_launcher 6.2.2 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] dev dependencies: - flutter_lints 3.0.1 [lints] - flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math async boolean_selector characters collection material_color_utilities meta source_span stream_channel string_scanner term_glyph web] transitive dependencies: - _flutterfire_internals 1.3.16 [collection firebase_core firebase_core_platform_interface flutter meta] - args 2.4.2 - asn1lib 1.5.0 - async 2.11.0 [collection meta] - boolean_selector 2.1.1 [source_span string_scanner] - cached_network_image_platform_interface 3.0.0 [flutter flutter_cache_manager] - cached_network_image_web 1.1.0 [cached_network_image_platform_interface flutter flutter_cache_manager] - characters 1.3.0 - clock 1.1.1 - collection 1.18.0 - connectivity_plus_platform_interface 1.2.4 [flutter meta plugin_platform_interface] - convert 3.1.1 [typed_data] - crypto 3.0.3 [typed_data] - csslib 0.17.3 [source_span] - dbus 0.7.10 [args ffi meta xml] - device_info_plus_platform_interface 7.0.0 [flutter meta plugin_platform_interface] - fake_async 1.3.1 [clock collection] - ffi 2.1.0 - file 7.0.0 [meta path] - firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface] - firebase_core_web 2.10.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - firebase_crashlytics_platform_interface 3.6.16 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - firebase_messaging_platform_interface 4.5.18 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 3.5.18 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta] - flutter_cache_manager 3.3.1 [clock collection file flutter http path path_provider rxdart sqflite uuid] - flutter_local_notifications_linux 4.0.0+1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories] - flutter_local_notifications_platform_interface 7.0.0+1 [flutter plugin_platform_interface] - flutter_plugin_android_lifecycle 2.0.17 [flutter] - flutter_secure_storage_linux 1.2.0 [flutter flutter_secure_storage_platform_interface] - flutter_secure_storage_macos 3.0.1 [flutter flutter_secure_storage_platform_interface] - flutter_secure_storage_platform_interface 1.0.2 [flutter plugin_platform_interface] - flutter_secure_storage_web 1.1.2 [flutter flutter_secure_storage_platform_interface flutter_web_plugins js] - flutter_secure_storage_windows 3.0.0 [ffi flutter flutter_secure_storage_platform_interface path path_provider win32] - flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math web] - graphs 2.3.1 [collection] - html 0.15.4 [csslib source_span] - http_parser 4.0.2 [collection source_span string_scanner typed_data] - js 0.6.7 [meta] - lints 3.0.0 - list_counter 1.0.2 - local_auth_platform_interface 1.0.8 [flutter plugin_platform_interface] - local_auth_windows 1.0.10 [flutter local_auth_platform_interface] - matcher 0.12.16 [async meta stack_trace term_glyph test_api] - material_color_utilities 0.5.0 [collection] - meta 1.10.0 - nm 0.5.0 [dbus] - octo_image 2.0.0 [flutter] - os_detect 2.0.1 - package_info_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface] - path 1.8.3 - path_parsing 1.0.1 [vector_math meta] - path_provider_android 2.2.1 [flutter path_provider_platform_interface] - path_provider_foundation 2.3.1 [flutter path_provider_platform_interface] - path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_platform_interface 2.1.1 [flutter platform plugin_platform_interface] - path_provider_windows 2.2.1 [ffi flutter path path_provider_platform_interface win32] - permission_handler_android 12.0.1 [flutter permission_handler_platform_interface] - permission_handler_apple 9.2.0 [flutter permission_handler_platform_interface] - permission_handler_html 0.1.0+2 [flutter flutter_web_plugins permission_handler_platform_interface] - permission_handler_platform_interface 4.0.2 [flutter meta plugin_platform_interface] - permission_handler_windows 0.2.0 [flutter permission_handler_platform_interface] - petitparser 6.0.2 [meta] - platform 3.1.3 - plugin_platform_interface 2.1.7 [meta] - pointycastle 3.7.3 [collection convert js] - rive 0.11.17 [collection flutter flutter_web_plugins http meta plugin_platform_interface rive_common] - rive_common 0.2.7 [collection ffi flutter flutter_web_plugins graphs http meta plugin_platform_interface] - rxdart 0.27.7 - shared_preferences_android 2.2.1 [flutter shared_preferences_platform_interface] - shared_preferences_foundation 2.3.4 [flutter shared_preferences_platform_interface] - shared_preferences_linux 2.3.2 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface] - shared_preferences_platform_interface 2.3.1 [flutter plugin_platform_interface] - shared_preferences_web 2.2.2 [flutter flutter_web_plugins shared_preferences_platform_interface web] - shared_preferences_windows 2.3.2 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface] - sky_engine 0.0.99 - source_span 1.10.0 [collection path term_glyph] - sprintf 7.0.0 - sqflite 2.3.0 [flutter sqflite_common path] - sqflite_common 2.5.0+2 [synchronized path meta] - stack_trace 1.11.1 [path] - stream_channel 2.1.2 [async] - string_scanner 1.2.0 [source_span] - synchronized 3.1.0 - term_glyph 1.2.1 - test_api 0.6.1 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph] - timezone 0.9.2 [path] - typed_data 1.3.2 [collection] - url_launcher_android 6.2.0 [flutter url_launcher_platform_interface] - url_launcher_ios 6.2.1 [flutter url_launcher_platform_interface] - url_launcher_linux 3.1.1 [flutter url_launcher_platform_interface] - url_launcher_macos 3.1.0 [flutter url_launcher_platform_interface] - url_launcher_platform_interface 2.2.0 [flutter plugin_platform_interface] - url_launcher_web 2.2.2 [flutter flutter_web_plugins url_launcher_platform_interface web] - url_launcher_windows 3.1.0 [flutter url_launcher_platform_interface] - uuid 4.2.2 [crypto sprintf meta] - vector_graphics 1.1.9+1 [flutter vector_graphics_codec] - vector_graphics_codec 1.1.9+1 - vector_graphics_compiler 1.1.9+1 [args meta path_parsing xml vector_graphics_codec path] - vector_math 2.1.4 - version 3.0.2 - web 0.3.0 - win32 5.1.1 [ffi] - win32_registry 1.1.2 [ffi win32] - xdg_directories 1.0.3 [meta path] - xml 6.5.0 [collection meta petitparser] ```

danagbemava-nc commented 8 months ago

Closing this as a duplicate of https://github.com/firebase/flutterfire/issues/12172