Flutter - 在 Firebase 消息传递中获取数组

时间:2021-05-21 06:34:40

标签: firebase flutter

在 Flutter 中,我尝试像这样在新的 firebase_messaging 10.0.0 中获取数组

import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:pushtest/functions/alert_messages.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pushtest/constant/constant.dart' as Constants;

class PushNotifications {
  FirebaseMessaging firebaseMessaging;

  initNotifications() {
    firebaseMessaging.requestPermission();
    firebaseMessaging.getToken().then((token) async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('firebaseToken', token);
    });
  }

  configuration(scaffold, location) {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var noti;
      message as Map;
      if (Platform.isIOS) {
        noti = message['message'];
      } else {
        noti = message['data']['message'];
      }
      if (location == 'navigation') {
        Messages.alert(scaffold.currentContext, noti);
      } else {
        Constants.message = noti;
      }
      return null;
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      var noti;
      if (Platform.isIOS) {
        noti = message['message'];
      } else {
        noti = message['data']['message'];
      }
      Constants.message = noti;
      return null;
    });
  }
}

问题:当我尝试做

<块引用>
 noti = message['message'];

返回

<块引用>

未为类型“RemoteMessage”定义运算符“[]”。尝试 定义运算符“[]”。

那么使用listen函数获取数组元素的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

如果您要发送 data 条消息,请执行以下操作:

noti = message.data['message'];