subscribe static method

Future<void> subscribe({
  1. required String appToken,
  2. required GlobalKey<NavigatorState> navigatorKey,
  3. String friendlyIdentifier = '',
  4. String? phoneNumber,
  5. Map<String, dynamic>? customFields,
  6. InngageWebViewProperties? inngageWebViewProperties,
})

Implementation

static Future<void> subscribe({
  required String appToken,
  required GlobalKey<NavigatorState> navigatorKey,
  String friendlyIdentifier = '',
  String? phoneNumber,
  Map<String, dynamic>? customFields,
  InngageWebViewProperties? inngageWebViewProperties,
}) async {


  try {
    //initialize firebase
    defaultApp = await Firebase.initializeApp();
  } catch (error) {
    if (getDebugMode()) {
      print(error.toString());
    }
  }
  //validation identifier
  if (friendlyIdentifier.isEmpty) {
    _identifier = await _getId();
  } else {
    _identifier = friendlyIdentifier;
  }
  _appToken = appToken;
  //set navigator key
  _navigatorKey = navigatorKey;

  //set inngage web view properties
  if (inngageWebViewProperties != null) {
    _inngageWebViewProperties = inngageWebViewProperties;
  }
  //set inngage web view properties
  if (phoneNumber != null) {
    _phoneNumber = phoneNumber;
  }

  //set customFields properties
  if (customFields != null) {
    _customFields = customFields;
  }
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  _firebaseMessaging.getInitialMessage().then((value) {
    try {
      _openCommonNotification(
          data: value!.data, appToken: _appToken, inBack: true);
    } catch (e) {}
  });
  await _firebaseMessaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  // Set the background messaging handler early on, as a named top-level function
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  if (Platform.isAndroid) {
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('launch_background');

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
            requestAlertPermission: false,
            requestBadgePermission: false,
            requestSoundPermission: false,
            onDidReceiveLocalNotification: (
              int id,
              String? title,
              String? body,
              String? payload,
            ) async {});

    final InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: (String? payload) async {
      if (payload != null) {
        debugPrint('notification payload: $payload');
        _openCommonNotification(
          data: json.decode(payload),
          appToken: _appToken,
        );
      }
    });
  }
  FirebaseMessaging.onMessage.listen((message) async {
    if (getDebugMode()) {
      print('onMessage ${message.data}');
    }
    if (Platform.isAndroid) {
      const AndroidNotificationDetails androidPlatformChannelSpecifics =
          AndroidNotificationDetails(
              'high_importance_channel', 'your channel name',
              channelDescription: 'your channel description',
              importance: Importance.max,
              priority: Priority.high,
              ticker: 'ticker');
      const NotificationDetails platformChannelSpecifics =
          NotificationDetails(android: androidPlatformChannelSpecifics);
      final titleNotification = message.data['title'];
      final messageNotification = message.data['message'];
      await flutterLocalNotificationsPlugin.show(
          0, titleNotification, messageNotification, platformChannelSpecifics,
          payload: json.encode(message.data));
    }
  });

  FirebaseMessaging.onMessageOpenedApp.listen((event) {
    if (getDebugMode()) {
      print('onMessageOpenedApp ${event.from}');
      print('onMessageOpenedApp ${event.messageType}');
    }
    _openCommonNotification(
      data: event.data,
      appToken: appToken,
    );
  });

  //request permission to iOS device
  if (Platform.isIOS) {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true, // Required to display a heads up notification
      badge: true,
      sound: true,
    );
  }

  //get device infos
  String? locale = await Devicelocale.currentLocale;
  List? languages = await Devicelocale.preferredLanguages;
  final deviceModel = await _getDeviceModel();
  final osDevice = await _getDeviceOS();
  final uuid = await _getUniqueId();
  final manufacturer = await _getDeviceManufacturer();
  final appVersion = await _getVersionApp();

  _firebaseMessaging.getToken().then(
    (String? registration) async {
      assert(registration != null);
      if (getDebugMode()) {
        print(registration);
      }
      final registerSubscriberRequest = RegisterSubscriberRequest(
        appInstalledIn: DateTime.now(),
        appToken: appToken,
        appUpdatedIn: DateTime.now(),
        customField: _customFields,
        appVersion: appVersion,
        deviceModel: deviceModel,
        sdk: '1',
        phoneNumber: _phoneNumber,
        deviceManufacturer: manufacturer,
        identifier: _identifier,
        osLanguage: languages![0] ?? '',
        osLocale: locale,
        osVersion: osDevice,
        registration: registration,
        uuid: uuid,
        platform: Platform.isAndroid ? 'Android' : 'iOS',
      );

      //make request subscription to inngage backend
      await _inngageNetwork.subscription(
        subscription: SubscriptionRequest(
          registerSubscriberRequest: registerSubscriberRequest,
        ),
      );
    },
  );
}