msgFromJson<T extends BaseMessage> method Null safety

T? msgFromJson<T extends BaseMessage>(
  1. Map<String, dynamic> json,
  2. {ChannelType? channelType,
  3. String? type}
)

Implementation

static T? msgFromJson<T extends BaseMessage>(
  Map<String, dynamic> json, {
  ChannelType? channelType,
  String? type,
}) {
  final cmd = type ?? json['type'] as String;
  T msg;
  //basemessage backward compatibility -
  if (json['custom'] != null) json['data'] = json['custom'];
  if (json['ts'] != null) json['created_at'] = json['ts'];
  if (json['msg_id'] != null) json['message_id'] = json['msg_id'];
  if (json['req_id'] != null) json['request_id'] = json['req_id'];
  //manually insert type if channel is provided
  if (channelType != null) json['channel_type'] = channelType.asString();

  if (T == UserMessage || CommandType.isUserMessage(cmd)) {
    msg = UserMessage.fromJson(json) as T;
  } else if (T == FileMessage || CommandType.isFileMessage(cmd)) {
    msg = FileMessage.fromJson(json) as T;
  } else if (T == AdminMessage || CommandType.isAdminMessage(cmd)) {
    msg = AdminMessage.fromJson(json) as T;
  } else {
    return null;
  }

  final metaArray = json['metaarray'];
  final metaArrayKeys = List<String>.from(json['metaarray_key_order'] ?? []);
  //NOTE: sorted_metaarray is from API, metaarray list is local,
  //metaarray map is from Web, so had to handle separately

  //local cmd case
  if (metaArray is List) {
    msg.metaArrays = metaArray
        .map((e) => MessageMetaArray.fromJson(e as Map<String, dynamic>))
        .toList();
  }
  //websocket cmd result case
  else if (metaArray is Map && metaArrayKeys.isNotEmpty) {
    msg.metaArrays = metaArrayKeys.map((e) {
      final value = List<String>.from(metaArray[e]);
      return MessageMetaArray(key: e, value: value);
    }).toList();
  }

  return msg;
}