flutterfirebase-cloud-messagingflutter2.0

The class 'FirebaseMessaging' doesn't have a default constructor Flutter 2


Before switching to Flutter 2, I was using an old version of firebaseMessaging without problems, and now I have the latest version.After upgrading I get the following error:

The class 'FirebaseMessaging' doesn't have a default constructor.


enter image description here

And:

The method 'configure' isn't defined for the type 'FirebaseMessaging'.


enter image description here

Full class:


class ShowNotifications {
static final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
 static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  new FlutterLocalNotificationsPlugin();

  static void initialization(){
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        android: initializationSettingsAndroid, iOS: initializationSettingsIOS);

    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);
  }




 static void showNotification(String title, String body) async {
    await _demoNotification(title, body);
  }

 static Future<void> _demoNotification(String title, String body) async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'channel_ID', 'channel name', 'channel description',
        importance: Importance.max,
        playSound: true,
        // sound: 'sound',
        // sound: true,
        showProgress: true,
        priority: Priority.high,
        ticker: 'test ticker');

    var iOSChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSChannelSpecifics);
    await flutterLocalNotificationsPlugin
        .show(0, title, body, platformChannelSpecifics, payload: 'test');
  }


 static Future onSelectNotification(String payload) async {
    showDialog(
   //   context: context,
      builder: (_) {
        return new AlertDialog(
          title: Text("PayLoad"),
          content: Text("Payload : $payload"),
        );
      },
    );
  }


 static notification(){
    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        showNotification(message['notification']['title'], message['notification']['body']);
        // print("onMessage: $message");
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");

      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");

      },

    );
  }
}

I was able to control this class from all the application pages.

What do I need to change with the new version. So that I can use the class as it was in the past.


Solution

  • Try to update your firebase_messaging package and also take care to use compatile packages for the other Firebase SDKs. I would recommend to copy the ones from the official documentation for each one you use.

    Here is a full example how the new Firebase Messaging SDK would work with the new API:

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:firebase_database/firebase_database.dart';
    import 'package:firebase_messaging/firebase_messaging.dart';
    import 'package:fluttertoast/fluttertoast.dart';
    
    import '../constants.dart';
    
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    
    final _database = FirebaseDatabase.instance;
    final _firestore = FirebaseFirestore.instance;
    final _auth = FirebaseAuth.instance;
    
    class MessagingService {
      static bool showToast = true;
      static String currentToken;
    
      static void initialize() async {
        await messaging.requestPermission(
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          criticalAlert: false,
          provisional: false,
          sound: true,
        );
    
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          if (message.notification != null) {
            print('Message also contained a notification: ${message.notification}');
          }
    
          if (showToast && message.notification != null) {
            Fluttertoast.showToast(
              msg: "${message.notification.title}: ${message.notification.body} ",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 1,
              //backgroundColor: Colors.red,
              //textColor: Colors.white,
              fontSize: 16.0,
            );
          }
        });
    
        messaging.onTokenRefresh.listen((String token) async {
          await syncToken();
        });
    
        await syncToken();
      }
    
      static Future<String> getToken() async {
        String token = await messaging.getToken();
        return token;
      }
    
      static Future syncToken() async {
        try {
          String token = await messaging.getToken();
          if (token != currentToken) {
            if (syncDatabase == databases.RealtimeDatabase) {
              await _database
                  .reference()
                  .child(
                      '$kNotificationTokensSyncBasePath${_auth.currentUser.uid}/$token')
                  .set(true);
            } else {
              await _firestore
                  .doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
                  .set({'$token': true}, SetOptions(merge: true));
            }
    
            currentToken = token;
          }
        } catch (e) {
          print(e);
        }
    
        return;
      }
    
      static Future unsyncToken(User user) async {
        try {
          String token = await messaging.getToken();
    
          if (syncDatabase == databases.RealtimeDatabase) {
            await _database
                .reference()
                .child('$kNotificationTokensSyncBasePath${user.uid}/$token')
                .set(null);
          } else {
            await _firestore
                .doc('$kNotificationTokensSyncBasePath${_auth.currentUser.uid}')
                .set({'$token': FieldValue.delete()}, SetOptions(merge: true));
          }
    
          currentToken = null;
        } catch (e) {
          print(e);
        }
    
        return;
      }
    }