参数类型“RemoteMessage”不能分配给参数类型“Map<String, dynamic>”

Posted

技术标签:

【中文标题】参数类型“RemoteMessage”不能分配给参数类型“Map<String, dynamic>”【英文标题】:The argument type 'RemoteMessage' can't be assigned to the parameter type 'Map<String, dynamic>' 【发布时间】:2021-11-13 20:43:56 【问题描述】:

我之前曾问过这个问题,但无法得到解决方案。如果我将代码 String getRideRequestId(Map message) 更改为 String getRideRequestId(var message) 代码,它会将消息发送到手机。它没有发送所需的rideDetails(第 82,83 和 84 行)。我也希望发送乘坐详情。请帮帮我。

这是错误日志: 正在运行 Gradle 任务“assembleDebug”... lib/Notifications/pushNotificationService.dart:17:48: 错误:参数类型“RemoteMessage”不能分配给参数类型“Map”。

'RemoteMessage' 来自'package:firebase_messaging_platform_interface/src/remote_message.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging_platform_interface-3.0.5/lib/src/ remote_message.dart')。 “地图”来自“飞镖:核心”。 检索RideRequestInfo(getRideRequestId(消息)); ^ lib/Notifications/pushNotificationService.dart:22:50:错误:无法将参数类型“RemoteMessage”分配给参数类型“Map”。 'RemoteMessage' 来自'package:firebase_messaging_platform_interface/src/remote_message.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging_platform_interface-3.0.5/lib/src/ remote_message.dart')。 “地图”来自“飞镖:核心”。 retrieveRideRequestInfo(getRideRequestId(message));

下面是我的代码:

Main.dart

import 'package:driver/AllScreens/carInfoScreen.dart';
import 'package:driver/configMaps.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:driver/AllScreens/mainScreen.dart';
import 'package:driver/AllScreens/registrationScreen.dart';
import 'package:driver/DataHandler/appData.dart';

import 'AllScreens/loginScreen.dart';

Future<void> backgroundHandler(RemoteMessage message) async

  print(message.data.toString());
  print(message.notification!.title);


void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(backgroundHandler);
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  currentFirebaseUser = FirebaseAuth.instance.currentUser;
  runApp(MyApp());


DatabaseReference usersRef = FirebaseDatabase.instance.reference().child("users");
DatabaseReference driversRef = FirebaseDatabase.instance.reference().child("drivers");
DatabaseReference newRequestRef = FirebaseDatabase.instance.reference().child("Ride Requests");
DatabaseReference rideRequestRef = FirebaseDatabase.instance.reference().child("drivers").child(currentFirebaseUser!.uid).child("newRide");

class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return ChangeNotifierProvider(
      create: (context) => AppData(),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Driver',
        theme: ThemeData(
          primarySwatch: Colors.green,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        initialRoute: FirebaseAuth.instance.currentUser == null ? LoginScreen.idScreen : MainScreen.idScreen,
        routes: 
          RegistrationScreen.idScreen: (context) => RegistrationScreen(),
          LoginScreen.idScreen: (context) => LoginScreen(),
          MainScreen.idScreen: (context) => MainScreen(),
          CarInfoScreen.idScreen: (context) => CarInfoScreen(),
        ,
      ),
    );
  

pushNotificationService.dart

import 'package:driver/Models/rideDetails.dart';
import 'package:driver/configMaps.dart';
import 'package:driver/main.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:io' show Platform;

class PushNotificationService 
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  Future initialize(context) async 
    FirebaseMessaging.onMessage.listen((RemoteMessage message) 
      RemoteNotification? notification = message.notification;
      androidNotification? android = message.notification?.android;

      retrieveRideRequestInfo(getRideRequestId(message));
    );

    FirebaseMessaging.onMessageOpenedApp.listen(
      (RemoteMessage message) 
        retrieveRideRequestInfo(getRideRequestId(message));
      ,
    );
  

  Future<String?> getToken() async 
    String? token = await firebaseMessaging.getToken();
    driversRef.child(currentFirebaseUser!.uid).child("token").set(token);

    print("Here is your token");
    print(token);

    firebaseMessaging.subscribeToTopic("alldrivers");
    firebaseMessaging.subscribeToTopic("allusers");
  

  // String getRideRequestId(var message) 

  String getRideRequestId(Map<String, dynamic> message) 
    String rideRequestId = "";

    if (Platform.isAndroid) 
      rideRequestId = message['data']['ride_request_id'];
     else 
      rideRequestId = message['ride_request_id'];
    
    return rideRequestId;
  

  void retrieveRideRequestInfo(String rideRequestId) 
    newRequestRef.child(rideRequestId).once().then((DataSnapshot dataSnapshot) 
      if (dataSnapshot.value != null) 
        double pickupLocationLat =
            double.parse(dataSnapshot.value['pickup']['latitude'].toString());
        double pickupLocationLng =
            double.parse(dataSnapshot.value['pickup']['longitude'].toString());
        String pickupAddress = dataSnapshot.value['pickup_address'].toString();

        double dropoffLocationLat =
            double.parse(dataSnapshot.value['dropoff']['latitude'].toString());
        double dropoffLocationLng =
            double.parse(dataSnapshot.value['dropoff']['longitude'].toString());
        String dropoffAddress =
            dataSnapshot.value['dropoff_address'].toString();

        String paymentMethod = dataSnapshot.value['payment_method'].toString();

        String rider_name = dataSnapshot.value["rider_name"].toString();
        String rider_phone = dataSnapshot.value["rider_phone"].toString();

        RideDetails rideDetails = RideDetails();
        rideDetails.ride_request_id = rideRequestId;
        rideDetails.pickup_address = pickupAddress;
        rideDetails.dropoff_address = dropoffAddress;
        rideDetails.pickup = LatLng(pickupLocationLat, pickupLocationLng);
        rideDetails.dropoff = LatLng(dropoffLocationLat, dropoffLocationLng);
        rideDetails.payment_method = paymentMethod;
        rideDetails.rider_name = rider_name;
        rideDetails.rider_phone = rider_phone;

        print("Information :: ");
        print(rideDetails.pickup_address);
        print(rideDetails.dropoff_address);
      
    );
  

rideDetails.dart

import 'package:google_maps_flutter/google_maps_flutter.dart';

class RideDetails 
  String? pickup_address;
  String? dropoff_address;
  LatLng? pickup;
  LatLng? dropoff;
  String? ride_request_id;
  String? payment_method;
  String? rider_name;
  String? rider_phone;

  RideDetails(this.pickup_address,
    this.dropoff_address,
    this.pickup, this.dropoff,
    this.ride_request_id,
    this.payment_method,
    this.rider_name,
    this.rider_phone);

【问题讨论】:

【参考方案1】:

您正试图在接受Map&lt;String,dynamic&gt; 的函数中发送RemoteMessage 类的对象。要发送正确格式的数据,请使用reference

将您的 RemoteMessage 转换为 Map,然后再次发送。如果要发送通知数据,可以这样发送:

retrieveRideRequestInfo(getRideRequestId(message.notification));

然后使用getRideRequestId(Map&lt;String, dynamic&gt; message) 检索数据:

 messageOfTitle=message["title"]

【讨论】:

感谢莫尼克的回复。我刚刚更改了您建议的代码。但是错误参数类型'RemoteNotification?不能分配给参数类型'动态函数(地图dart.dev/go/non-promo-property(remote_message.dart:75) . 我想我把整个代码弄混了。请你把代码按正确的顺序放在这里吗。谢谢。我对 Flutter 很陌生。【参考方案2】:

我知道您正在关注 udemy 课程源代码。 这是解决方案。如下更改 getRiderRequestid 函数。

  String getRideRequestId(RemoteMessage message)
  
    String rideRequestId = "";
    if(Platform.isAndroid)
    
       rideRequestId = message.data['ride_request_id'] ; //message['data']['ride_request_id'];
    
    else
    
       rideRequestId = message.data['ride_request_id'];
    

    return rideRequestId;
  

【讨论】:

以上是关于参数类型“RemoteMessage”不能分配给参数类型“Map<String, dynamic>”的主要内容,如果未能解决你的问题,请参考以下文章

颤振列表错误参数类型'List'不能分配给参数类型'String'

获取错误“未知”类型的参数不能分配给“错误”类型的参数 |空值'

参数类型“对象?”不能分配给参数类型'String'最新版本

参数类型“字符串”不能分配给参数类型“目录”

参数类型“Type”不能分配给参数类型“FirebaseUser”

参数类型“字符串”不能分配给参数类型“对象?函数(对象?,对象?)?