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

Firebase Messaging - Null check operator used on a null value #8864

Closed helloalbin closed 2 years ago

helloalbin commented 2 years ago

Bug report

Describe the bug When using FCM with riverpod, an error is thrown in the console.

Steps to reproduce

Follow the code provided in https://stackoverflow.com/questions/72038598/how-to-update-state-in-a-fcm-handler-with-statenotifierprovider.

My PushNotificationService

class PushNotificationService {
  final fcm = FirebaseMessaging.instance;

  Future initialise(WidgetRef ref) async {
    /// foreground handler
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // Call foreground handler
    });

    FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {
         // call background handler
      });

    /// handler if the app has been opened from a background state
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {});
  }
}

Error strack trace

I/flutter (16036): Null check operator used on a null value I/flutter (16036): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:181:53) I/flutter (16036): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:102:16) I/flutter (16036): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)

Expected behavior

No error should be thrown


Flutter version 3.0.0

darshankawar commented 2 years ago

When using FCM with riverpod,

Does the same error occur without riverpod ? If so, can you provide a complete minimal reproducible code sample that triggers the log ?

helloalbin commented 2 years ago

The same issue occures even without riverpod as well.

Code sample https://github.com/helloalbin/fcm_bug

maheshj01 commented 2 years ago

Hi @helloalbin, I looked at your code sample and you seem to be using an older version of firebase_messaging can you please try using the latest version firebase_messaging: ^11.4.1? Can you share what are the steps to reproduce the issue? I ran your code sample and tried pushing notifications and clicking them on IOS, but I don't see any error.

code sample ```dart import 'dart:async'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() async { runZonedGuarded>(() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]); try { runApp(const MainView()); } catch (e, ex) {} }, (error, stack) { // FirebaseCrashlytics.instance.recordError(error, stack, fatal: true); }); } class MainView extends StatefulWidget { const MainView({Key? key}) : super(key: key); @override State createState() => _MainStartViewState(); } class _MainStartViewState extends State { @override initState() { super.initState(); PushNotificationService().initialise(); } @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: GlobalKey(), home: Container(), // navigatorObservers: [ // FirebaseAnalyticsObserver(analytics: FirebaseAnalytics.instance), // ], ); } } class PushNotificationService { final fcm = FirebaseMessaging.instance; Future initialise() async { /// foreground handler FirebaseMessaging.onMessage.listen((RemoteMessage message) {}); try { FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {}); } catch (err) { // Dont do anything } /// handler if the app has been opened from a background state FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {}); } } ```
flutter doctor -v (mac) ``` [✓] Flutter (Channel stable, 3.0.1, on macOS 12.3 21E230 darwin-arm, locale en-IN) • Flutter version 3.0.1 at /Users/mahesh/Documents/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision fb57da5f94 (3 days ago), 2022-05-19 15:50:29 -0700 • Engine revision caaafc5604 • Dart version 2.17.1 • DevTools version 2.12.2 [✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at /Users/mahesh/Library/Android/sdk • Platform android-32, build-tools 31.0.0 • ANDROID_HOME = /Users/mahesh/Library/Android/sdk • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763) • All Android licenses accepted. [!] Xcode - develop for iOS and macOS (Xcode 13.2.1) • Xcode at /Applications/Xcode.app/Contents/Developer ! CocoaPods 1.10.2 out of date (1.11.0 is recommended). CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side. Without CocoaPods, plugins will not work on iOS or macOS. For more info, see https://flutter.dev/platform-plugins To upgrade see https://guides.cocoapods.org/using/getting-started.html#installation for instructions. [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2021.1) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763) [✓] IntelliJ IDEA Community Edition (version 2021.2.1) • IntelliJ at /Applications/IntelliJ IDEA CE.app • Flutter plugin version 61.2.4 • Dart plugin version 212.5080.8 [✓] VS Code (version 1.66.2) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.40.0 [✓] Connected device (4 available) • Redmi K20 Pro (mobile) • 192.168.1.2:5555 • android-arm64 • Android 11 (API 30) • iPhone 12 Pro (mobile) • 19FD0231-BFF0-441D-B584-AD94C4084525 • ios • com.apple.CoreSimulator.SimRuntime.iOS-15-2 (simulator) • macOS (desktop) • macos • darwin-arm64 • macOS 12.3 21E230 darwin-arm • Chrome (web) • chrome • web-javascript • Google Chrome 101.0.4951.64 [✓] HTTP Host Availability • All required HTTP hosts are available ! Doctor found issues in 1 category. ```
helloalbin commented 2 years ago

I tested with the latest version and the issue still exists. The updated dependencies are

firebase_core: ^1.17.1
firebase_analytics: ^9.1.9
firebase_crashlytics: ^2.8.1
dio_firebase_performance: ^0.3.1-dev.3
firebase_messaging: ^11.4.1
firebase_dynamic_links: ^4.2.5
firebase_remote_config: ^2.0.8
firebase_performance: ^0.7.1+5
firebase_in_app_messaging: ^0.6.0+15
cloud_firestore: ^3.1.17

The exception strack trace gets printed when we start the application. I am using Windows + Android 11 (API 30)

Output of flutter doctor

[√] Flutter (Channel stable, 3.0.0, on Microsoft Windows [Version 10.0.19042.1706], locale en-IN)
    • Flutter version 3.0.0 at C:\Apps\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision ee4e09cce0 (5 weeks ago), 2022-05-09 16:45:18 -0700
    • Engine revision d1b9a6938a
    • Dart version 2.17.0
    • DevTools version 2.12.2
maheshj01 commented 2 years ago

Thanks for the info @helloalbin, I was able to reproduce the error on Redmi k20 pro (Android 11), The error is reproduced by running the below code sample at this line

FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {});

code sample ```dart import 'dart:async'; import 'package:firebase_analytics/firebase_analytics.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/material.dart'; import 'package:flutter/services.dart'; void main() async { runZonedGuarded>(() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true); final FirebaseAnalytics analytics = FirebaseAnalytics.instance; FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError; SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]); try { runApp(const MainView()); } catch (e, ex) {} }, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack, fatal: true)); } class MainView extends StatefulWidget { const MainView({Key? key}) : super(key: key); @override State createState() => _MainStartViewState(); } class _MainStartViewState extends State { @override initState() { super.initState(); PushNotificationService().initialise(); } @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: GlobalKey(), home: Container(), navigatorObservers: [ FirebaseAnalyticsObserver(analytics: FirebaseAnalytics.instance), ], ); } } class PushNotificationService { final fcm = FirebaseMessaging.instance; Future initialise() async { /// foreground handler FirebaseMessaging.onMessage.listen((RemoteMessage message) {}); try { FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {}); } catch (err) { // Dont do anything } /// handler if the app has been opened from a background state FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {}); } } ```

logs

Launching lib/main.dart on Redmi K20 Pro in debug mode...
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
W/FlutterActivityAndFragmentDelegate(17435): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
Connecting to VM Service at ws://127.0.0.1:59480/p9B2H3Jc_Vs=/ws
I/FIAM.Headless(17435): Successfully fetched 0 messages from backend
D/FRCPlugin(17435): Sending fetchTimeout: 60
I/flutter (17435): ----------------FIREBASE CRASHLYTICS----------------
I/flutter (17435): Null check operator used on a null value
I/flutter (17435): #0      MethodChannelFirebaseMessaging.registerBackgroundMessageHandler
I/flutter (17435): #1      FirebaseMessagingPlatform.onBackgroundMessage=
I/flutter (17435): #2      FirebaseMessaging.onBackgroundMessage
I/flutter (17435): #3      PushNotificationService.initialise
I/flutter (17435): #4      _MainStartViewState.initState
I/flutter (17435): #5      StatefulElement._firstBuild
I/flutter (17435): #6      ComponentElement.mount
I/flutter (17435): #7      Element.inflateWidget
I/flutter (17435): #8      Element.updateChild
I/flutter (17435): #9      RenderObjectToWidgetElement._rebuild
I/flutter (17435): ----------------------------------------------------
I/evercode.triag(17435): ProcessProfilingInfo new_methods=8939 is saved saved_to_disk=1 resolve_classes_delay=8000
E/FirebaseCrashlytics(17435): Cannot send reports. Timed out while fetching settings.
flutter doctor -v (mac) ``` [✓] Flutter (Channel stable, 3.0.2, on macOS 12.4 21F79 darwin-arm, locale en-IN) • Flutter version 3.0.2 at /Users/mahesh/Documents/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision cd41fdd495 (5 days ago), 2022-06-08 09:52:13 -0700 • Engine revision f15f824b57 • Dart version 2.17.3 • DevTools version 2.12.2 [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0-rc4) • Android SDK at /Users/mahesh/Library/Android/sdk • Platform android-32, build-tools 33.0.0-rc4 • ANDROID_HOME = /Users/mahesh/Library/Android/sdk • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 13.2.1) • Xcode at /Applications/Xcode.app/Contents/Developer • CocoaPods version 1.11.2 [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2021.2) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840) [✓] IntelliJ IDEA Community Edition (version 2021.2.1) • IntelliJ at /Applications/IntelliJ IDEA CE.app • Flutter plugin version 61.2.4 • Dart plugin version 212.5080.8 [✓] VS Code (version 1.67.2) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.42.0 [✓] Connected device (3 available) • sdk gphone arm64 (mobile) • emulator-5554 • android-arm64 • Android 11 (API 30) (emulator) • macOS (desktop) • macos • darwin-arm64 • macOS 12.4 21F79 darwin-arm • Chrome (web) • chrome • web-javascript • Google Chrome 102.0.5005.61 [✓] HTTP Host Availability • All required HTTP hosts are available • No issues found! ```
russellwheatley commented 2 years ago

As per the documentation, you need to put the onBackgroundMessage function outside of a class, at the top of your file as a top-level function. See Firebase messaging example for implementation.