createSpace function

Future<String?> createSpace(
  1. dynamic context,
  2. dynamic ref, {
  3. required String name,
  4. String? description,
  5. File? spaceAvatar,
  6. String? parentRoomId,
  7. dynamic roomVisibility,
  8. bool createDefaultChat = false,
})

Create a new space as the current client

Implementation

Future<String?> createSpace(
  BuildContext context,
  WidgetRef ref, {
  /// The name of the new new space
  required String name,

  /// Set the starting topic
  String? description,
  File? spaceAvatar,
  String? parentRoomId,
  RoomVisibility? roomVisibility,
  bool createDefaultChat = false,
}) async {
  EasyLoading.show(status: L10n.of(context).creatingSpace);
  try {
    final sdk = await ref.read(sdkProvider.future);
    final config = sdk.api.newSpaceSettingsBuilder();
    config.setName(name);
    if (description != null && description.isNotEmpty) {
      config.setTopic(description.trim());
    }
    if (spaceAvatar != null && spaceAvatar.path.isNotEmpty) {
      // space creation will upload it
      config.setAvatarUri(spaceAvatar.path);
    }
    if (parentRoomId != null) {
      config.setParent(parentRoomId);
    }
    if (roomVisibility != null) {
      config.setVisibility(roomVisibility.name);
    }
    final client = ref.read(alwaysClientProvider);
    final roomId = (await client.createActerSpace(config.build())).toString();
    if (parentRoomId != null) {
      final space = await ref.read(spaceProvider(parentRoomId).future);
      await space.addChildRoom(roomId, false);
      // spaceRelations come from the server and must be manually invalidated
      ref.invalidate(spaceRelationsProvider(parentRoomId));
      ref.invalidate(spaceRemoteRelationsProvider(parentRoomId));
    }
    EasyLoading.dismiss();

    if (createDefaultChat) {
      if (!context.mounted) return null;
      final chatId = await createChat(
        context,
        ref,
        name: L10n.of(context).defaultChatName(name),
        parentId: roomId,
        suggested: true,
      );
      if (chatId != null) {
        // close the UI if the chat successfully created
        EasyLoading.dismiss();
      }
    }
    return roomId;
  } catch (e, s) {
    _log.severe('Failed to create space', e, s);
    if (!context.mounted) {
      EasyLoading.dismiss();
      return null;
    }
    EasyLoading.showError(
      L10n.of(context).creatingSpaceFailed(e),
      duration: const Duration(seconds: 3),
    );
    return null;
  }
}