initialize method

Future<void> initialize()

Implementation

Future<void> initialize() async {
  if (_disposed) {
    throw const FcmActionsInitializationException(
      'A disposed FcmActionsClient cannot be initialized.',
    );
  }
  if (_initialized) return;
  try {
    WidgetsFlutterBinding.ensureInitialized();
    await _initializeFirebase();
    await BackgroundDispatcher.configure(config);
    messaging.registerBackgroundHandler();

    final templates = <NotificationMessage>[
      if (config.actions.isNotEmpty)
        parser.parseMap(<String, Object?>{
          'message_id': 'fcm_actions_registered_actions',
          'actions': config.actions.map((action) => action.toJson()).toList(),
        }),
    ];
    final localLaunch = await localNotifications.initialize(
      defaultAndroidIcon: config.defaultAndroidIcon,
      requestPermission: config.requestPermission,
      categoryTemplates: templates,
      onResponse: _handleLocalResponse,
    );
    await localNotifications.createChannels(channels.channels.values);
    if (config.requestPermission) await messaging.requestPermission();
    await messaging.configureForegroundPresentation();

    _subscriptions
      ..add(
        messaging.foregroundMessages.listen(
          (message) => unawaited(_handleForeground(message)),
          onError: _streamError,
        ),
      )
      ..add(
        messaging.openedMessages.listen(
          (message) =>
              unawaited(_handleOpened(message, NotificationState.resumed)),
          onError: _streamError,
        ),
      );
    WidgetsBinding.instance.addObserver(this);
    _initialized = true;

    await _publishPendingBackgroundEvents();
    final initialMessage = await messaging.getInitialMessage();
    if (initialMessage != null) {
      await _handleOpened(initialMessage, NotificationState.terminated);
    }
    if (localLaunch != null) await _handleLocalResponse(localLaunch);
    await retryPendingActions();
  } on FcmActionsException {
    rethrow;
  } on Object catch (error, stackTrace) {
    config.logger.log(
      FcmLogLevel.error,
      'Initialization failed.',
      error: error,
      stackTrace: stackTrace,
    );
    throw FcmActionsInitializationException(
      'Could not initialize notification services.',
      cause: error,
    );
  }
}