startDirectChat method

Future<String> startDirectChat(
  1. String mxid, {
  2. bool? enableEncryption,
  3. List<StateEvent>? initialState,
  4. bool waitForSync = true,
  5. Map<String, dynamic>? powerLevelContentOverride,
  6. CreateRoomPreset? preset = CreateRoomPreset.trustedPrivateChat,
})

Returns an existing direct room ID with this user or creates a new one. By default encryption will be enabled if the client supports encryption and the other user has uploaded any encryption keys.

Implementation

Future<String> startDirectChat(
  String mxid, {
  bool? enableEncryption,
  List<StateEvent>? initialState,
  bool waitForSync = true,
  Map<String, dynamic>? powerLevelContentOverride,
  CreateRoomPreset? preset = CreateRoomPreset.trustedPrivateChat,
}) async {
  // Try to find an existing direct chat
  final directChatRoomId = getDirectChatFromUserId(mxid);
  if (directChatRoomId != null) return directChatRoomId;

  enableEncryption ??=
      encryptionEnabled && await userOwnsEncryptionKeys(mxid);
  if (enableEncryption) {
    initialState ??= [];
    if (!initialState.any((s) => s.type == EventTypes.Encryption)) {
      initialState.add(StateEvent(
        content: {
          'algorithm': supportedGroupEncryptionAlgorithms.first,
        },
        type: EventTypes.Encryption,
      ));
    }
  }

  // Start a new direct chat
  final roomId = await createRoom(
    invite: [mxid],
    isDirect: true,
    preset: preset,
    initialState: initialState,
    powerLevelContentOverride: powerLevelContentOverride,
  );

  if (waitForSync && getRoomById(roomId) == null) {
    // Wait for room actually appears in sync
    await waitForRoomInSync(roomId, join: true);
  }

  await Room(id: roomId, client: this).addToDirectChat(mxid);

  return roomId;
}