createNotificationFromJsonData method

  1. @override
Future<bool> createNotificationFromJsonData(
  1. Map<String, dynamic> mapData
)
override

Creates a new notification based on a map that is similar to the map produced by the toMap() method of a NotificationModel object.

The mapData parameter is a Map that represents the model of the notification, including the content, schedule, buttons, and localizations.

This method returns a Future that resolves to true if the notification was successfully created, or false if an error occurred.

This method is typically used to recreate a notification from data that was previously saved or transmitted in a different format, such as JSON. To use this method, you must first create a Map of the notification data, using a format that is similar to the output of the toMap() method of a NotificationModel object. Then, pass this map to the createNotificationFromJsonData() method to create the notification.

Implementation

@override
Future<bool> createNotificationFromJsonData(
    Map<String, dynamic> mapData) async {
  try {
    // FCM data arrives as a flat Map<String, String>, so work on a typed copy.
    // Normalize every top-level string that parses as a JSON object/array —
    // this covers content/schedule/actionButtons, the `localizations` block and
    // any future add-on key, without the core needing to know them by name.
    final Map<String, dynamic> normalized =
        Map<String, dynamic>.from(mapData);
    for (final String key in normalized.keys.toList()) {
      final dynamic value = normalized[key];
      if (value is String) {
        try {
          final dynamic decoded = json.decode(value);
          if (decoded is Map || decoded is List) normalized[key] = decoded;
        } catch (_) {
          // Not JSON — keep the original string value.
        }
      }
    }

    // Invalid Notification
    NotificationModel? notificationModel =
        NotificationModel().fromMap(normalized);
    if (notificationModel == null) {
      throw Exception('Notification map data is invalid');
    }

    // Forward the normalized known sections AND preserve any extra top-level
    // keys from the payload (e.g. `localizations` from a push, or other add-on
    // data) so the native side still receives the original JSON shape.
    final Map<String, dynamic> data = notificationModel.toMap();
    for (final MapEntry<String, dynamic> entry in normalized.entries) {
      data.putIfAbsent(entry.key, () => entry.value);
    }

    final bool wasCreated = await methodChannel.invokeMethod(
        CHANNEL_METHOD_CREATE_NOTIFICATION, data);

    return wasCreated;
  } catch (e) {
    return false;
  }
}