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.61k stars 3.95k forks source link

🐛 [firebase_messaging] Not receiving onBackgroundMessage calls, onMessageOpenedApp and getInitialMessage #6825

Closed shubh420 closed 3 years ago

shubh420 commented 3 years ago

Bug report

Describe the bug I have added firebase_messaging in my flutter app using this guide- https://firebase.flutter.dev/docs/messaging/notifications/ . I have done all the steps. the notification payload message with only notification object is being rendered by fcm itself in background, app terminated state and foreground(local_notifications) . Even the notification plus data message payload which I am hitting from postman is also being rendered properly. But I am having these below issues :

  1. I am not getting any onBackgroundMessage callback in my app. Even when fcm is receiving the notification message payload and rendering them(I have debug logs andflutterLocalNotificationsPlugin.show inside the onBackgroundMessage callback, which should show two notification, one rendered by fcm and one by flutterLocalNotificationsPlugin ).

  2. I am not getting any callback when I click on the notifications FirebaseMessaging.instance.getInitialMessage and FirebaseMessaging.onMessageOpenedApp.listen are not getting triggered

Steps to reproduce

Sample code below

Expected behavior

A clear and concise description of what you expected to happen.

Sample file and code

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  await flutterLocalNotificationsPlugin
      .show(0, 'local notif title', 'local notif body', null, payload: 'item x');
}

void main() async {
  // Initialize Firebase.
  WidgetsFlutterBinding
      .ensureInitialized(); //WidgetsFlutterBinding.ensureInitialized is for firebase
  await Firebase.initializeApp();

  if (CommonMethods.isRunningOnWeb() == false) {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {

      NotificationDetails notificationDetails;
      if (message.notification.apple.imageUrl != null) {
        final String bigPicturePath = await CommonMethods.downloadAndSaveFile(
            message.notification.apple.imageUrl, 'bigPicture.jpg');

        IOSNotificationDetails iOSPlatformChannelSpecifics =
            IOSNotificationDetails(attachments: <IOSNotificationAttachment>[
          IOSNotificationAttachment(bigPicturePath)
        ]);

        notificationDetails =
            NotificationDetails(iOS: iOSPlatformChannelSpecifics);
      }

      flutterLocalNotificationsPlugin
          .show(Random().nextInt(1 << 5), message.notification.title,
              message.notification.body, notificationDetails,
              payload: 'item x');

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
            requestAlertPermission: true,
            requestBadgePermission: true,
            requestSoundPermission: true,
            onDidReceiveLocalNotification: (
              int id,
              String title,
              String body,
              String payload,
            ) async {

            });

    final InitializationSettings initializationSettings =
        InitializationSettings(
      iOS: initializationSettingsIOS,
    );

    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String payload) async {

    });
  }

  runZonedGuarded(
      () async => runApp(
            Phoenix(
                child: MultiProvider(
              providers: [
                ChangeNotifierProvider(
                    create: (_) => LoggedInUserPlusCompanyData()),
                ChangeNotifierProvider(create: (_) => AttendanceModel()),
                //  ChangeNotifierProvider(create: (_) => CompanyDataProvider())
              ],
              child: MyApp(userID, companyID),
            )),
          ), (e, s) {

  });
}

class MyApp extends StatefulWidget {

  MyApp(this.userID, this.companyID);

  // This widget is the root of your application.
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  company.CompanyDataAfterRegisteringCompany companyData;
  CleverTapPlugin _clevertapPlugin;
  static AppsflyerSdk appsflyerSdk;

  static FirebaseAnalytics analytics = FirebaseAnalytics();
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  void initState() {
    super.initState();

    // Run code required to handle interacted messages in an async function
    // as initState() must not be async

    if (CommonMethods.isRunningOnWeb() == false) {
      setupInteractedMessage();
    }

    initPlatformState();
    activateCleverTapFlutterPluginHandlers();
    CleverTapPlugin.setDebugLevel(3);

    initAppsFlyerSdk(appsFlyerOptions);

    _requestPermissions();
  }

  // It is assumed that all messages contain a data field with the key 'type'
  Future<void> setupInteractedMessage() async {
    // Get any messages which caused the application to open from
    // a terminated state.
    RemoteMessage initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();

    // If the message also contains a data property with a "type" of "chat",
    // navigate to a chat screen
    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }

    // Also handle any interaction when the app is in the background via a
    // Stream listener
    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage).onError((e) {
      CustomLogger.debug("onMessageOpenedApp, onError: " + e.toString(),
          TAG: NotCommonConstantData.FCM_TAG);
    });
  }

  void _handleMessage(RemoteMessage message) {
    CustomLogger.debug("_handleMessage, message: " + message.toString(),
        TAG: NotCommonConstantData.FCM_TAG);

  }

  void _requestPermissions() {
    /*flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        IOSFlutterLocalNotificationsPlugin>()
        ?.requestPermissions(
      alert: true,
      badge: true,
      sound: true,
    );*/
  }

  @override
  Widget build(BuildContext context) {

    MaterialApp materialApp = getMaterialApp();

    return materialApp;
  }
}

Additional context

I am using some analytics library like firebase analytics and clevertap and appsflyer


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` shubhashishdangwal@Shubhashishs-MacBook-Pro Salarybox % flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel beta, 2.2.2, on macOS 11.2.3 20D91 darwin-arm, locale en-IN) [!] Android toolchain - develop for Android devices (Android SDK version 30.0.3) ! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses [✓] Xcode - develop for iOS and macOS [✓] Chrome - develop for the web [!] Android Studio ✗ Unable to find bundled Java version. [✓] Android Studio (version 4.2) [✓] VS Code (version 1.56.2) [✓] Connected device (1 available) ! Doctor found issues in 2 categories. ```

Flutter dependencies

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

Click To Expand ``` Dart SDK 2.13.3 Flutter SDK 2.2.2 salarybox 1.0.24+41 dependencies: - appsflyer_sdk 6.2.4+4-nullsafety [flutter] - camera 0.8.1+3 [camera_platform_interface flutter pedantic quiver] - clevertap_plugin 1.2.0 [flutter] - cupertino_icons 1.0.3 - device_info 2.0.2 [flutter device_info_platform_interface] - dio 4.0.0 [http_parser path] - firebase_analytics 8.2.0 [firebase_analytics_platform_interface firebase_analytics_web firebase_core flutter meta] - firebase_core 1.4.0 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_crashlytics 2.1.1 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace] - firebase_messaging 10.0.4 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine] - flutter_local_notifications 8.1.1+1 [flutter flutter_local_notifications_platform_interface platform timezone] - flutter_pdfview 1.1.0 [flutter] - flutter_phoenix 1.0.0 [flutter] - flutter_svg 0.19.3 [flutter meta path_drawing vector_math xml] - flutter_time_picker_spinner 1.0.6+1 [flutter] - fluttercontactpicker 4.5.1 [flutter contact_picker_platform_interface contact_picker_web] - geocode 1.0.1 [http] - geolocator 7.2.0+1 [flutter geolocator_platform_interface geolocator_web] - get 4.1.4 [flutter] - google_maps_flutter 2.0.6 [flutter flutter_plugin_android_lifecycle google_maps_flutter_platform_interface] - google_maps_flutter_web 0.3.0+2 [flutter flutter_web_plugins google_maps_flutter_platform_interface google_maps meta sanitize_html stream_transform] - google_place 0.4.3 [http] - http 0.13.3 [async http_parser meta path pedantic] - http_interceptor 0.4.1 [flutter http] - image_picker 0.8.2 [flutter flutter_plugin_android_lifecycle image_picker_for_web image_picker_platform_interface] - infinite_scroll_pagination 3.1.0 [flutter sliver_tools] - intl 0.17.0 [clock path] - intl_phone_field 1.4.4 [flutter] - json_annotation 3.1.1 - logger 1.0.0 - month_picker_dialog 0.3.3 [flutter flutter_localizations intl flutter_cupertino_localizations rxdart] - multi_select_flutter 3.1.8 [flutter] - ntp 2.0.0 - open_file 3.1.0 [flutter ffi] - package_info_plus 1.0.3 [flutter package_info_plus_platform_interface package_info_plus_linux package_info_plus_macos package_info_plus_windows package_info_plus_web] - path_provider 2.0.2 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows] - permission_handler 6.1.3 [flutter meta permission_handler_platform_interface] - photo_view 0.12.0 [flutter] - provider 5.0.0 [collection flutter nested] - razorpay_flutter 1.2.7 [flutter eventify] - share 2.0.4 [meta mime flutter] - shared_preferences 2.0.6 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows] - sms_autofill 1.3.1 [pin_input_text_field flutter] - sticky_headers 0.2.0 [flutter] - universal_html 2.0.8 [async csslib charcode collection html meta source_span typed_data universal_io] - url_launcher 6.0.9 [flutter meta url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] dev dependencies: - build_runner 1.11.5 [args async build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style glob graphs http_multi_server io js logging meta mime path pedantic pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml] - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data] - json_serializable 3.5.1 [analyzer build build_config json_annotation meta path source_gen] transitive dependencies: - _fe_analyzer_shared 14.0.0 [meta] - analyzer 0.41.2 [_fe_analyzer_shared args cli_util collection convert crypto glob meta package_config path pub_semver source_span watcher yaml] - args 2.1.1 - async 2.6.1 [meta collection] - boolean_selector 2.1.0 [source_span string_scanner] - build 1.6.2 [analyzer async convert crypto glob logging meta path] - build_config 0.4.6 [checked_yaml json_annotation meta path pubspec_parse yaml] - build_daemon 2.1.10 [built_collection built_value http_multi_server logging pedantic path pool shelf shelf_web_socket stream_transform watcher web_socket_channel] - build_resolvers 1.5.3 [analyzer build crypto graphs logging meta path package_config pool pub_semver] - build_runner_core 6.1.10 [async build build_config build_resolvers collection convert crypto glob graphs logging meta path package_config pedantic pool timing watcher yaml] - built_collection 5.1.0 - built_value 8.1.1 [built_collection collection fixnum meta] - camera_platform_interface 2.0.1 [flutter meta plugin_platform_interface cross_file stream_transform] - characters 1.1.0 - charcode 1.2.0 - checked_yaml 1.0.4 [json_annotation source_span yaml] - cli_util 0.3.3 [meta path] - clock 1.1.0 - code_builder 3.7.0 [built_collection built_value collection matcher meta] - collection 1.15.0 - contact_picker_platform_interface 4.5.1 [flutter meta plugin_platform_interface] - contact_picker_web 4.5.1 [flutter flutter_web_plugins js contact_picker_platform_interface] - convert 2.1.1 [charcode typed_data] - cross_file 0.3.1+3 [flutter meta] - crypto 3.0.1 [collection typed_data] - csslib 0.17.0 [source_span] - dart_style 1.3.12 [analyzer args path pub_semver source_span] - device_info_platform_interface 2.0.1 [flutter meta plugin_platform_interface] - eventify 1.0.0 - fake_async 1.2.0 [clock collection] - ffi 1.1.2 - file 6.1.2 [meta path] - firebase 9.0.1 [http http_parser js] - firebase_analytics_platform_interface 2.0.1 [flutter meta] - firebase_analytics_web 0.3.0+1 [firebase firebase_analytics_platform_interface flutter flutter_web_plugins meta] - firebase_core_platform_interface 4.0.1 [collection flutter meta plugin_platform_interface] - firebase_core_web 1.1.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - firebase_crashlytics_platform_interface 3.1.0 [collection firebase_core flutter meta plugin_platform_interface] - firebase_messaging_platform_interface 3.0.3 [firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 2.0.3 [firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta] - fixnum 1.0.0 - flutter_cupertino_localizations 1.0.1 [flutter flutter_localizations] - flutter_local_notifications_platform_interface 4.0.1 [flutter plugin_platform_interface] - flutter_localizations 0.0.0 [flutter intl characters clock collection meta path typed_data vector_math] - flutter_plugin_android_lifecycle 2.0.2 [flutter] - flutter_web_plugins 0.0.0 [flutter js characters collection meta typed_data vector_math] - geolocator_platform_interface 2.3.1 [flutter plugin_platform_interface vector_math meta] - geolocator_web 2.0.4 [flutter flutter_web_plugins geolocator_platform_interface] - glob 2.0.1 [async collection file path pedantic string_scanner] - google_maps 5.1.0 [js_wrapping meta] - google_maps_flutter_platform_interface 2.1.0 [collection flutter meta plugin_platform_interface stream_transform] - graphs 0.2.0 - html 0.15.0 [csslib source_span] - http_multi_server 2.2.0 [async] - http_parser 4.0.0 [charcode collection source_span string_scanner typed_data] - image_picker_for_web 2.1.0 [flutter flutter_web_plugins image_picker_platform_interface meta] - image_picker_platform_interface 2.2.0 [flutter http meta plugin_platform_interface cross_file] - io 0.3.5 [meta path string_scanner] - js 0.6.3 - js_wrapping 0.7.0 [js] - logging 1.0.1 - matcher 0.12.10 [stack_trace] - meta 1.3.0 - mime 1.0.0 - nested 1.0.0 [flutter] - package_config 1.9.3 [path charcode] - package_info_plus_linux 1.0.2 [package_info_plus_platform_interface flutter path] - package_info_plus_macos 1.1.1 [flutter] - package_info_plus_platform_interface 1.0.1 [flutter meta plugin_platform_interface] - package_info_plus_web 1.0.2 [http package_info_plus_platform_interface flutter flutter_web_plugins meta] - package_info_plus_windows 1.0.2 [package_info_plus_platform_interface ffi flutter win32] - path 1.8.0 - path_drawing 0.4.1+1 [vector_math meta path_parsing flutter] - path_parsing 0.1.4 [vector_math meta] - path_provider_linux 2.0.0 [path xdg_directories path_provider_platform_interface flutter] - path_provider_macos 2.0.0 [flutter] - path_provider_platform_interface 2.0.1 [flutter meta platform plugin_platform_interface] - path_provider_windows 2.0.1 [path_provider_platform_interface meta path flutter ffi win32] - pedantic 1.11.1 - permission_handler_platform_interface 3.6.0 [flutter meta plugin_platform_interface] - petitparser 3.1.0 [meta] - pin_input_text_field 3.3.1 [flutter] - platform 3.0.0 - plugin_platform_interface 2.0.1 [meta] - pool 1.5.0 [async stack_trace] - process 4.2.1 [file path platform] - pub_semver 2.0.0 [collection] - pubspec_parse 0.1.8 [checked_yaml json_annotation pub_semver yaml] - quiver 3.0.1 [matcher] - rxdart 0.24.1 - sanitize_html 2.0.0 [html meta] - shared_preferences_linux 2.0.0 [flutter file meta path path_provider_linux shared_preferences_platform_interface] - shared_preferences_macos 2.0.0 [shared_preferences_platform_interface flutter] - shared_preferences_platform_interface 2.0.0 [flutter] - shared_preferences_web 2.0.0 [shared_preferences_platform_interface flutter flutter_web_plugins meta] - shared_preferences_windows 2.0.0 [shared_preferences_platform_interface flutter file meta path path_provider_platform_interface path_provider_windows] - shelf 1.2.0 [async collection http_parser path stack_trace stream_channel] - shelf_web_socket 0.2.4+1 [shelf stream_channel web_socket_channel] - sky_engine 0.0.99 - sliver_tools 0.2.5 [flutter] - source_gen 0.9.10+3 [analyzer async build dart_style glob meta path pedantic source_span] - source_span 1.8.1 [collection path term_glyph] - stack_trace 1.10.0 [path] - stream_channel 2.1.0 [async] - stream_transform 2.0.0 - string_scanner 1.1.0 [charcode source_span] - term_glyph 1.2.0 - test_api 0.3.0 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher] - timezone 0.7.0 [path] - timing 0.1.1+3 [json_annotation] - typed_data 1.3.0 [collection] - universal_io 2.0.4 [collection crypto meta typed_data] - url_launcher_linux 2.0.0 [flutter] - url_launcher_macos 2.0.0 [flutter] - url_launcher_platform_interface 2.0.4 [flutter plugin_platform_interface] - url_launcher_web 2.0.1 [flutter flutter_web_plugins meta url_launcher_platform_interface] - url_launcher_windows 2.0.0 [flutter] - vector_math 2.1.0 - watcher 1.0.0 [async path pedantic] - web_socket_channel 1.2.0 [async crypto stream_channel] - win32 2.2.5 [ffi] - xdg_directories 0.2.0 [meta path process] - xml 4.5.1 [collection convert meta petitparser] - yaml 3.1.0 [collection source_span string_scanner] ```

markusaksli-nc commented 3 years ago

Hi @shubh420 The part of the documentation you linked only really describes how to set up the code but have you carefully followed all of the steps in https://firebase.flutter.dev/docs/messaging/apple-integration

The background message handler will only get called on iOS if the content_available flag is set to true in the message payload. This is done automatically for data-only messages without a notification key but if you want to trigger the handler with regular shown notifications you need to set the key yourself.

As for the other handlers not working could you try replicating this with the official example code to make sure this isn't something in your codebase?

https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example/lib

Thank you

google-oss-bot commented 3 years ago

Hey @shubh420. We need more information to resolve this issue but there hasn't been an update in 7 weekdays. I'm marking the issue as stale and if there are no new updates in the next 7 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

google-oss-bot commented 3 years ago

Since there haven't been any recent updates here, I am going to close this issue.

@shubh420 if you're still experiencing this problem and want to continue the discussion just leave a comment here and we are happy to re-open this.