首页 > 解决方案 > 错误:无法处理本地通知上的方法调用

问题描述

我正在使用本地通知。我想在 onMessage 中显示带有本地通知的通知,但我不断收到此错误:Failed to handle method call。在谷歌搜索答案后,请继续参考应用程序图标。

将应用程序图标更改为我抽屉中的名称后,我仍然收到错误消息。

我已经尝试过 @mipmap/ic_launcher 和 mipmap/ic_launcher 两者。app_icon 是我命名的 playstore-icon.png 的名称

抽屉图像

andriodManifest.xml

这是我的代码

class MyProfile extends StatefulWidget {
  @override
  _MyProfileState createState() => _MyProfileState();
}

class _MyProfileState extends State<MyProfile> {
  Map dataset;
  bool state = false;
  String selected = "first";

  FirebaseMessaging messaging = FirebaseMessaging.instance;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  AndroidNotificationChannel channel = AndroidNotificationChannel(
    'faithmeetslove', // id
    'High Importance Notifications', // title
    'This channel is used for important notifications.', // description
    importance: Importance.max,
  );

  Future<void> saveTokenToDatabase(String token) async {
    String userId = auth.currentUser.uid;
    await firestore.collection("users").doc(userId).update({
      'tokens': token,
    });
  }

  @override
  void initState() {
    super.initState();
    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: AndroidInitializationSettings("playstore-icon.png"),
            iOS: IOSInitializationSettings(
              requestAlertPermission: false,
              requestBadgePermission: false,
              requestSoundPermission: false,
            ));
    getData();
    getTokens();
    getUserLocation();
  }

  getTokens() async {
    String token = await FirebaseMessaging.instance.getToken();
    await saveTokenToDatabase(token);
    FirebaseMessaging.instance.onTokenRefresh.listen(saveTokenToDatabase);
    if (Platform.isIOS) {
      FirebaseMessaging.instance.requestPermission();
    }
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage message) {
      if (message != null) {
        Navigator.pushNamed(context, message.data['view']);
      }
    });
    print('User granted permission: ${settings.authorizationStatus}');
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Message data: ${message.data['key']}');

      //message.data
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;

      // If `onMessage` is triggered with a notification, construct our own
      // local notification to show to users using the created channel.

      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channel.description,
                icon: android?.smallIcon,
                // other properties...
              ),
            ));
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      debugPrint('A new onMessageOpenedApp event was published!');
      // _navigator.currentState.pushNamed('/' + message.data['view']);
    });
  }

  getData() async {
    setState(() {
      state = true;
    });
    final datastore =
        await firestore.collection('users').doc(auth.currentUser.uid).get();
    if (mounted) {
      setState(() {
        setState(() {
          dataset = datastore.data();
          state = false;
        });
      });
    }
  }

标签: flutterdartpush-notification

解决方案


我认为您缺少一些初始化步骤,例如我没有看到您在哪里initalize调用FlutterLocalNotificationsPlugin. 我在这里写的方式是结合远程和本地消息传递,希望对您有所帮助。

首先,确保您已将这些行添加到AndroidManifest.xml您想要的图标中:

<meta-data
  android:name="com.google.firebase.messaging.default_notification_icon"
  android:resource="@drawable/ic_notification"/>
<meta-data
  android:name="com.google.firebase.messaging.default_notification_channel_id"
  android:value="mychannel" /> 

然后完成初始化步骤,像这样,我称之为initState

void initNotifications() async {
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings notificationSettings =
      await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  if (notificationSettings.authorizationStatus ==
      AuthorizationStatus.authorized) {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'mychannel', 
      'title',
      'description',
      importance: Importance.max,
    );

    final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();

    flutterLocalNotificationsPlugin.initialize(
        InitializationSettings(
            android:
                AndroidInitializationSettings('@drawable/ic_notification'),
            iOS: IOSInitializationSettings()),
        onSelectNotification: _onSelectNotification);

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      if (message.notification == null) {
        return;
      }

      RemoteNotification notification = message.notification!;

      if (notification.android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
                android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channel.description,
            )));
      }
    });


    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      // do something with message
    });

    messaging.getInitialMessage().then((RemoteMessage? message) {

      if (message == null) {
        return;
      }

      // do something with message

    });
  }
}

在上面的代码_onSelectNotification中,当用户在应用程序处于活动状态时推送通知时将运行一个函数,我认为只在 Android 上。这个函数看起来像:

Future _onSelectNotification(String? payload) {
   // do something with payload
}

推荐阅读