我的Flutter应用在从FCM接收到后台通知时崩溃。

huangapple go评论63阅读模式
英文:

My Flutter app crashes on background notification from FCM

问题

我一直在尝试在Flutter中创建一个FCM项目,已经两三天了。我认为逐步讲述我遇到的困难会更准确。

首先,我正常创建了我的项目。然后,我使用FlutterFire CLI将Firebase集成到我的项目中。我的第一个错误是Execution failed for task ':app:mapDebugSourceSetPaths',我遇到了这个错误。我通过将GMS版本从x.x.x.10更改为x.x.x.15来解决了这个问题。

然后,我将Firebase Messaging添加到我的项目中,将minSdk版本设置为19并通过了。然后,我根据文档中的代码更新了我的应用程序,以便接收后台通知。在成功接收第一个通知后,当第二个通知到来时,应用程序崩溃并显示FATAL错误。我尝试了一次,也许是因为调试模式,但是我再次遇到了相同的错误,消息已经接收了两次,一旦日志到达,应用程序就崩溃了。

我的代码和Flutter输出如下:

import 'package:firebase_core/firebase_core.dart';
import 'dart:developer';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'firebase_options.dart';
import 'package:flutter/material.dart';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();

  print("Handling a background message: ${message.messageId}");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Simple App",
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
        brightness: Brightness.light,
      ),
      home: const MyHomePage(title: 'Simple App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void showNotification() {
    setState(() {
      _counter++;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(
          "Kimlik Doğrulama Servisi",
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
      ),
      body: Center(
        child: Container()
      ),
    );
  }
}

输出如下:

D/FLTFireMsgReceiver(19336): broadcast received for message
W/FirebaseMessaging(19336): Unable to log event: analytics library is missing
W/FirebaseMessaging(19336): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
D/CompatibilityChangeReporter(19336): Compat change id reported: 160794467; UID 10868; state: ENABLED
I/flutter (19336): Handling a background message: 0:1687133276773552%48e9d64e48e9d64e
W/FirebaseMessaging(19336): Unable to log event: analytics library is missing

D/FLTFireMsgReceiver(19336): broadcast received for message
D/AndroidRuntime(19336): Shutting down VM
E/AndroidRuntime(19336): FATAL EXCEPTION: main
E/AndroidRuntime(19336): Process: com.example.madmin_mobile, PID: 19336
E/AndroidRuntime(19336): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Class.isInterface()' on a null object reference
...
(以下是一堆堆栈跟踪信息,略去)
...
I/Process (19336): Sending signal. PID: 19336 SIG: 9
Lost connection to device.

请帮助我使我的应用程序正常工作。

英文:

I've been trying to make an fcm project with flutter for 2-3 days. I think it would be more accurate to tell about the difficulties I experienced in turn.

First, I created my project normally. Then I integrated Firebase into my project with flutterfire cli. My first error is Execution failed for task &#39;:app:mapDebugSourceSetPaths&#39;. i got the error. I solved the problem by changing the GMS version from x.x.x.10 to x.x.x.15.

Then I added firebase messaging to my project, set the minSdk error to 19 and passed. Then I updated my application to receive backgroud notifications in accordance with the code in the documentation. After receiving the 1st notification properly, on the 2nd notification the app crashes with FATAL. I tried again saying maybe it's because of the debug mode, but I got the same error again, broadcast received for message for the 2nd time.
The application crashes as soon as the log arrives.

My code and flutter output;

import &#39;package:firebase_core/firebase_core.dart&#39;;
import &#39;dart:developer&#39;;

import &#39;package:firebase_messaging/firebase_messaging.dart&#39;;
import &#39;firebase_options.dart&#39;;
import &#39;package:flutter/material.dart&#39;;

Future&lt;void&gt; _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();

  print(&quot;Handling a background message: ${message.messageId}&quot;);
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}


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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: &quot;Simple App&quot;,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
        brightness: Brightness.light,
      ),
      home: const MyHomePage(title: &#39;Simple App&#39;),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  int _counter = 0;

  void showNotification() {
    setState(() {
      _counter++;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(
          &quot;Kimlik Doğrulama Servisi&quot;,
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
      ),
      body: Center(
        child: Container()
      ),
    );
  }
}

:: OUTPUT ::

D/FLTFireMsgReceiver(19336): broadcast received for message
W/FirebaseMessaging(19336): Unable to log event: analytics library is missing
W/FirebaseMessaging(19336): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
D/CompatibilityChangeReporter(19336): Compat change id reported: 160794467; UID 10868; state: ENABLED
I/flutter (19336): Handling a background message: 0:1687133276773552%48e9d64e48e9d64e
W/FirebaseMessaging(19336): Unable to log event: analytics library is missing

D/FLTFireMsgReceiver(19336): broadcast received for message
D/AndroidRuntime(19336): Shutting down VM
E/AndroidRuntime(19336): FATAL EXCEPTION: main
E/AndroidRuntime(19336): Process: com.example.madmin_mobile, PID: 19336
E/AndroidRuntime(19336): java.lang.NullPointerException: Attempt to invoke virtual method &#39;boolean java.lang.Class.isInterface()&#39; on a null object reference
E/AndroidRuntime(19336):        at java.lang.Class.isAssignableFrom(Class.java:589)
E/AndroidRuntime(19336):        at android.os.Parcel.readParcelableCreatorInternal(Parcel.java:4865)
E/AndroidRuntime(19336):        at android.os.Parcel.readParcelableInternal(Parcel.java:4778)
E/AndroidRuntime(19336):        at android.os.Parcel.readValue(Parcel.java:4544)
E/AndroidRuntime(19336):        at android.os.Parcel.readValue(Parcel.java:4324)
E/AndroidRuntime(19336):        at android.os.Parcel.-$$Nest$mreadValue(Unknown Source:0)
E/AndroidRuntime(19336):        at android.os.Parcel$LazyValue.apply(Parcel.java:4422)
E/AndroidRuntime(19336):        at android.os.Parcel$LazyValue.apply(Parcel.java:4381)
E/AndroidRuntime(19336):        at android.os.BaseBundle.getValueAt(BaseBundle.java:394)
E/AndroidRuntime(19336):        at android.os.BaseBundle.getValue(BaseBundle.java:374)
E/AndroidRuntime(19336):        at android.os.BaseBundle.getValue(BaseBundle.java:357)
E/AndroidRuntime(19336):        at android.os.BaseBundle.get(BaseBundle.java:696)
E/AndroidRuntime(19336):        at android.os.Bundle.getParcelable(Bundle.java:947)
E/AndroidRuntime(19336):        at android.content.Intent.getParcelableExtra(Intent.java:9558)
E/AndroidRuntime(19336):        at io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundExecutor.executeDartCallbackInBackgroundIsolate(FlutterFirebaseMessagingBackgroundExecutor.java:235)
E/AndroidRuntime(19336):        at io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService.lambda$onHandleWork$0(FlutterFirebaseMessagingBackgroundService.java:146)
E/AndroidRuntime(19336):        at io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService$$ExternalSyntheticLambda0.run(Unknown Source:4)
E/AndroidRuntime(19336):        at android.os.Handler.handleCallback(Handler.java:942)
E/AndroidRuntime(19336):        at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(19336):        at android.os.Looper.loopOnce(Looper.java:226)
E/AndroidRuntime(19336):        at android.os.Looper.loop(Looper.java:313)
E/AndroidRuntime(19336):        at android.app.ActivityThread.main(ActivityThread.java:8757)
E/AndroidRuntime(19336):        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(19336):        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
E/AndroidRuntime(19336):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
I/Process (19336): Sending signal. PID: 19336 SIG: 9
Lost connection to device.

make my app work properly.

答案1

得分: 4

我正在使用Android 33时遇到相同的问题。
他们似乎正在解决这个问题:
https://github.com/firebase/flutterfire/issues/11142

由于这是一个关键问题,正在等待修复。

更新:修复现已发布,使用firebase_messaging版本^14.6.4:
https://pub.dev/packages/firebase_messaging/changelog

英文:

I am experiencing the same with Android 33.
They seem to be addressing it here:
https://github.com/firebase/flutterfire/issues/11142

Waiting for a fix as this is a critical issue.

Update: fix is now out with
firebase_messaging: ^14.6.4
https://pub.dev/packages/firebase_messaging/changelog

答案2

得分: 0

我最终通过在依赖项中添加 firebase_analytics 来解决了这个问题。

英文:

i was facing to this issue but I finally fix the issue by adding

firebase_analytics

in the dependencies

huangapple
  • 本文由 发表于 2023年6月19日 08:46:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定