未处理的异常:NoSuchMethodError:类“RemoteMessage”没有实例方法“[]”

Posted

技术标签:

【中文标题】未处理的异常:NoSuchMethodError:类“RemoteMessage”没有实例方法“[]”【英文标题】:Unhandled Exception: NoSuchMethodError: Class 'RemoteMessage' has no instance method '[]' 【发布时间】:2021-11-24 14:50:10 【问题描述】:

我正在尝试向手机发送推送通知。消息已发送,但内容未发送,并出现以下错误:未处理的异常:NoSuchMethodError:类“RemoteMessage”没有实例方法“[]”。 有几个类似的问题,但没有多大帮助。所有的建议都会被采纳。

pushNotificationService.dart

   import 'package:driver/Models/rideDetails.dart';
    import 'package:driver/Notifications/notificationDialog.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:flutter/material.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) 
          if (message.notification != null) 
            retrieveRideRequestInfo(getRideRequestId(message), context);
          
        );
    
        FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) 
    
          retrieveRideRequestInfo(getRideRequestId(message), context);
    
          );
      
    
      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(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, BuildContext context) 
        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 riderName = dataSnapshot.value["rider_name"].toString();
            String riderPhone = 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 = riderName;
            rideDetails.rider_phone = riderPhone;
    
            print("Information :: ");
            print(rideDetails.pickup_address);
            print(rideDetails.dropoff_address);
    
            showDialog(
                context: context,
                barrierDismissible: false,
              builder: (BuildContext context) => NotificationDialog(rideDetails: rideDetails,),
            );
          
        );
      
    
   

     **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);
  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(),
        ,
      ),
    );
  

【问题讨论】:

【参考方案1】:

改一下

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

到这里

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

【讨论】:

以上是关于未处理的异常:NoSuchMethodError:类“RemoteMessage”没有实例方法“[]”的主要内容,如果未能解决你的问题,请参考以下文章

获取“未处理的异常:NoSuchMethodError:方法'map'在null上被调用”

未处理的异常:NoSuchMethodError:方法“findAncestorStateOfType”在 null 上被调用

Flutter,无法提取 api 数据:(未处理的异常:NoSuchMethodError:方法 'map' 在 null 上被调用。)

未处理的异常:NoSuchMethodError:在 null 上调用了方法“[]”(json 解析)

未处理的异常:NoSuchMethodError:在 null 上调用了方法“toRawHandle”

未处理的异常:NoSuchMethodError:在 null 上调用了方法“[]”。尝试调用:[](“is_ordered”)。检查空字段 Firebase [重复]