< Flutter UIKit />
UTD Live Room Kit
Видео-live-комнаты с камерой ведущего, плитками гостей и управлением сценой.
import 'package:utd_live_room_kit/utd_live_room_kit.dart';
UTDLiveRoom(
appId: '<utd-app-id>',
appKey: '<utd-app-key>', // publishable; no backend needed
userId: 'user123',
userName: 'Jane',
roomId: 'room456',
roomOwnerId: 'owner789',
adminIds: const {'mod1', 'mod2'},
config: const UTDLiveRoomConfig(maxGuestTiles: 3),
);3
Плитки гостей
4
Роли
Drop-in
Полный UI
PiP
+ сворачивание
< utd_live_room_kit />
Ключевые возможности
Готовый к продакшену Flutter-пакет для интерактивных видео-live-комнат на базе LiveKit и UTD Stream Engine. Полноэкранная камера ведущего с до тремя плавающими плитками гостей, серверно-авторитетные роли (ведущий, гость, админ, зрители), динамические операции на сцене для приглашения со-публикующих, чат в реальном времени, медиаконтроли с маршрутизацией звука и сворачивание/PiP.
Готовый интерфейс live-комнаты с плитками ведущего и гостей
Неограниченная сцена прямой трансляции (без сетки мест)
Поток сцены: запрос на выступление, приглашение от ведущего, удаление
Серверно-авторитетные роли: ведущий, гость, админ (модераторы), зрители
Управление медиа ведущим: принудительное заглушение/включение, остановка камеры, удаление со сцены
Чат через data-канал в реальном времени с дедупликацией
Многоуровневое переподключение (лёгкое <15s, полное <60s, выход >60s)
Сворачивание в плавающее окно с опциональным Android OS PiP
Видеоэффекты через TrackProcessor (в паре с Video Effects Kit)
Учётные данные без бэкенда: выпуск токена по appKey с bearer-авторизацией для каждого пользователя
< utd_live_room_kit />
Начать
Установка
flutter pub add utd_live_room_kitОткрыть на pub.dev
Видео-live-комнаты с камерой ведущего, плитками гостей и управлением сценой.
< utd_live_room_kit />
Справочник API
Main widget
The drop-in LiveKit live-streaming room widget.
UTDLiveRoomwidgetconst UTDLiveRoom({required String appId, required String appKey, required String userId, required String userName, required String roomId, required String roomOwnerId, Set<String> adminIds, ..., UTDLiveRoomConfig config, void Function(UTDRoomController)? onControllerReady, ...})A LiveKit-based video live room. The host's camera fills the screen as the background; up to maxGuestTiles invited guests appear as floating video tiles. Audience watch + chat and may request to go live.
Параметры
appIdStringобязательныйApp ID for the UTD Stream Engine (X-App-Id).
appKeyStringобязательныйPublishable app key (no backend). The kit mints tokens directly with X-App-Key; the server secret never ships.
userIdStringобязательныйLocal user's identity.
userNameStringобязательныйLocal user's display name.
roomIdStringобязательныйRoom / LiveKit room name to join.
roomOwnerIdStringобязательныйIdentity of the room owner (becomes host); everyone else joins as audience.
adminIdsSet<String>По умолчанию = const {}Identities the owner will promote to admin (moderators) once present in the room.
adminIdsResolverFuture<Set<String>> Function()?По умолчанию = nullAsync source for adminIds resolved after join; the owner self-promotes them via the role endpoint.
adminIdsNowSet<String> Function()?По умолчанию = nullOptional sync probe for the admin list at token time (no waiting).
configUTDLiveRoomConfigПо умолчанию = const UTDLiveRoomConfig()Behaviour, theming, and section/tile override configuration.
onControllerReadyvoid Function(UTDRoomController)?По умолчанию = nullCalled once the room controller is created (use it to drive the room imperatively).
onConnectionChangedvoid Function(bool)?По умолчанию = nullCalled when the connection succeeds (true) or fails (false).
onConnectErrorvoid Function(Object, StackTrace)?По умолчанию = nullCalled on connect failure; if null the kit shows its built-in connect-error view.
controllerUTDRoomController?По умолчанию = nullReuse an existing already-connected controller, e.g. restoring from a minimized overlay.
Room controller
Imperative facade over the room: connection lifecycle, participants, roles, stage, moderation, and sub-controllers.
UTDRoomControllerconstructorUTDRoomController()Creates a room controller that wires up the seat/stage, media, chat, minimize, and PiP sub-controllers.
initApimethodvoid initApi({String baseUrl, String engineBaseUrl, String? appId, String? appKey})Initializes the engine REST clients (token host + in-room ops host). Must be called before connect to use the backend APIs.
Параметры
baseUrlStringПо умолчанию = UTDApiClient.defaultBaseUrlToken/auth host (POST /api/v1/token).
engineBaseUrlStringПо умолчанию = UTDApiClient.defaultEngineBaseUrlIn-room ops host (stage, roles, bans, participants).
appIdString?По умолчанию = nullApp ID sent as the X-App-Id header.
appKeyString?По умолчанию = nullPublishable app key (no-backend mint credential, sent as X-App-Key).
connectmethodasyncFuture<void> connect({required String url, required String token, int seatCount = 9, bool enableMicOnJoin = false, bool useSpeaker = true, Map<String, String> userAttributes = const {}, String? roomName, String? hostIdentity})Connects to the LiveKit room, initializes seats/stage, starts chat + media listeners, and begins participant/speaking tracking.
Параметры
urlStringобязательныйLiveKit server URL from the token response.
tokenStringобязательныйLiveKit access token from generateToken.
seatCountintПо умолчанию = 9Tile-layout capacity (host slot + guest tiles); the engine stage is uncapped.
enableMicOnJoinboolПо умолчанию = falseEnable the local mic immediately after connecting.
useSpeakerboolПо умолчанию = trueRoute audio to the speaker (preferring Bluetooth) on join.
userAttributesMap<String, String>По умолчанию = const {}Participant attributes (avatar, name, VIP frame, etc.) published after connect.
roomNameString?По умолчанию = nullRoom name used for in-room REST calls; falls back to the LiveKit room name.
hostIdentityString?По умолчанию = nullOwner identity, used to detect when the host leaves and end the live for others.
generateTokenmethodasyncFuture<UTDTokenResponse> generateToken({required String identity, required String roomName, required String roomOwnerId, String type = 'live_stream', String? name, String role = 'audience', ..., Map<String, dynamic>? metadata})Mints a LiveKit token via the engine and, in app-key mode, applies the returned per-user bearer to the in-room clients. Throws UTDBannedException on a 403 ban.
Параметры
identityStringобязательныйUser identity to mint the token for.
roomNameStringобязательныйTarget room name.
roomOwnerIdStringобязательныйIdentity of the room owner.
typeStringПо умолчанию = 'live_stream'Engine product type; live_stream is the unbounded seatless stage.
nameString?По умолчанию = nullDisplay name.
roleStringПо умолчанию = 'audience'Requested role; the engine clamps non-owners to audience.
deviceIdString?По умолчанию = nullStable per-install id for single-active-session enforcement; auto-resolved when omitted.
metadataMap<String, dynamic>?По умолчанию = nullExtra metadata to embed in the token.
leavemethodasyncFuture<void> leave()Leaves the room: a host broadcasts _live_ended first, then all listeners/timers are cancelled and LiveKit is disconnected.
disposemethodvoid dispose()Releases all controller resources (timers, subscriptions, notifiers, sub-controllers, and REST clients). Idempotent.
requestToSpeakmethodasyncFuture<Map<String, dynamic>?> requestToSpeak()Local audience member asks to go on stage (transient host-side signal). Returns a result map on success, null on failure.
inviteToSpeakmethodasyncFuture<Map<String, dynamic>?> inviteToSpeak(String targetIdentity)Host/admin invites a user onto the stage (grants publish immediately, no accept/decline). Returns null when guest tiles are full.
Параметры
targetIdentityStringобязательныйIdentity of the user to invite on stage.
approveSpeakerRequestmethodasyncFuture<Map<String, dynamic>?> approveSpeakerRequest(String identity)Host/admin approves a pending stage request by adding the user to the stage. Returns null when guest tiles are full.
Параметры
identityStringобязательныйIdentity of the requester to approve.
changeRolemethodasyncFuture<UTDRoleChangeResult> changeRole({required String targetIdentity, required String role})Owner-only: changes a participant's role via the engine. Throws on REST error (403/404/409/422) so callers can surface a message.
Параметры
targetIdentityStringобязательныйIdentity of the participant whose role changes.
roleStringобязательныйNew role (e.g. 'admin', 'audience').
banUsermethodasyncFuture<bool> banUser(String identity, {String? reason, int? durationSeconds, bool global = false})Bans a user. Room-scoped by default; pass global true for a project-wide ban. Returns true on success.
Параметры
identityStringобязательныйIdentity to ban.
reasonString?По умолчанию = nullOptional ban reason.
durationSecondsint?По умолчанию = nullBan duration; null = permanent.
globalboolПо умолчанию = falseWhen true, bans across the whole project rather than this room.
kickParticipantmethodasyncFuture<bool> kickParticipant(String targetIdentity)Host/admin: removes a user from the broadcast entirely (engine-side disconnect). Returns true on success.
Параметры
targetIdentityStringобязательныйIdentity to remove from the room.
setRemoteMicEnabledmethodasyncFuture<bool> setRemoteMicEnabled(String targetIdentity, bool enabled)Host/admin: server-side force-mute or unmute another participant's microphone. Returns true on success.
Параметры
targetIdentityStringобязательныйIdentity whose mic is controlled.
enabledboolобязательныйTrue to enable, false to mute.
sendChatMessagemethodasyncFuture<void> sendChatMessage(String text)Sends a chat message to the room (delegates to the chat controller).
Параметры
textStringобязательныйMessage body to send.
participantsStreamgetterasyncStream<List<UTDParticipant>> get participantsStreamStream of all room participants; emits on join/leave/attribute/metadata changes.
Возвращает: Stream<List<UTDParticipant>> — Live participant list.
roleChangeStreamgetterasyncStream<UTDRoleChangeEvent> get roleChangeStreamStream of role changes (_role_change) for all participants — owner promotions/demotions and engine auto-corrections.
Возвращает: Stream<UTDRoleChangeEvent> — Role-change events.
isConnectedgetterbool get isConnectedWhether the room is currently in the connected state.
Возвращает: bool — True when connected.
isLocalHostgetterbool get isLocalHostWhether this device is the room owner (host).
Возвращает: bool — True if the local user is the host.
activeSpeakerspropertyfinal ValueNotifier<Set<String>> activeSpeakersSet of user IDs currently speaking, driven by LiveKit active-speaker events plus a 300ms backstop poll.
Возвращает: ValueNotifier<Set<String>> — Speaking identities.
onBannedcallbackvoid Function(UTDBanNotice notice)? onBannedFired once when the local user is banned (data message, removal, or token 403). The widget wires this to show the banned dialog and leave.
Возвращает: void Function(UTDBanNotice)? — Ban callback.
Media controller
Mic, camera, speaker, and host preview/Go-Live control (UTDRoomController.mediaController).
startPreviewmethodasyncFuture<LocalVideoTrack?> startPreview({CameraPosition position = CameraPosition.front})Creates a local, unpublished camera preview for the host 'Go Live' screen (no remote sees it). Idempotent.
Параметры
positionCameraPositionПо умолчанию = CameraPosition.frontFront/back camera to open the preview with.
goLivemethodasyncFuture<void> goLive({bool withMic = true})Host 'Go Live': publishes the camera (reusing the preview track for no flicker) and, by default, enables the mic.
Параметры
withMicboolПо умолчанию = trueAlso enable the microphone when going live.
setMicrophoneEnabledmethodasyncFuture<void> setMicrophoneEnabled(bool enabled)Sets the local microphone to a specific enabled state and updates isMicEnabled.
Параметры
enabledboolобязательныйTrue to enable, false to mute.
setCameraEnabledmethodasyncFuture<void> setCameraEnabled(bool enabled)Sets the local camera to a specific state (requests camera permission first) and updates isCameraEnabled.
Параметры
enabledboolобязательныйTrue to enable, false to disable.
switchCameramethodasyncFuture<void> switchCamera()Flips between front and back camera for the active (published or preview) camera track, re-attaching any video-effects processor.
setSpeakerOnmethodasyncFuture<void> setSpeakerOn(bool on)Turns the speaker on/off. Off truly silences the room (disables remote audio tracks), not just reroutes to the earpiece.
Параметры
onboolобязательныйTrue for loudspeaker, false to silence the room.
setVideoProcessormethodasyncFuture<void> setVideoProcessor(TrackProcessor<VideoProcessorOptions>? processor)Attaches (or detaches with null) a beauty/filter processor to the active local camera track at runtime, without re-capturing.
Параметры
processorTrackProcessor<VideoProcessorOptions>?обязательныйEffects processor to attach; null detaches.
isMicEnabledpropertyfinal ValueNotifier<bool> isMicEnabledReactive local microphone enabled state, kept in sync with server/host-initiated mutes.
Возвращает: ValueNotifier<bool> — Mic state.
canPublishpropertyfinal ValueNotifier<bool> canPublishWhether the local participant may publish mic/camera; driven by LiveKit permission events. Gate publish UI on this.
Возвращает: ValueNotifier<bool> — Publish permission.
isPreviewingpropertyfinal ValueNotifier<bool> isPreviewingWhether a local, unpublished camera preview (host 'Go Live' screen) is active.
Возвращает: ValueNotifier<bool> — Preview-active state.
Stage REST API
Direct REST client for the live_stream stage endpoints (UTDStageApi). The stage is the unbounded publisher set: host plus host-invited co-publishers.
getStagemethodasyncFuture<Map<String, dynamic>> getStage({required String roomName})Returns the current stage publishers as { members: [{ identity, name, role }] }. GET /api/v1/rooms/:name/stage.
Параметры
roomNameStringобязательныйRoom name.
addToStagemethodasyncFuture<Map<String, dynamic>> addToStage({required String roomName, required String targetIdentity, required String actorIdentity})Host/admin invites a user onto the stage (grants A/V publish). POST /api/v1/rooms/:name/stage/add.
Параметры
roomNameStringобязательныйRoom name.
targetIdentityStringобязательныйUser being added to the stage.
actorIdentityStringобязательныйHost/admin performing the action (dual-mode fallback).
removeFromStagemethodasyncFuture<Map<String, dynamic>> removeFromStage({required String roomName, required String targetIdentity, required String actorIdentity})Host/admin removes a user from the stage (revokes publish). POST /api/v1/rooms/:name/stage/remove.
Параметры
roomNameStringобязательныйRoom name.
targetIdentityStringобязательныйUser being removed from the stage.
actorIdentityStringобязательныйHost/admin performing the action.
leaveStagemethodasyncFuture<Map<String, dynamic>> leaveStage({required String roomName, required String identity})A co-publisher steps down from the stage on their own. POST /api/v1/rooms/:name/stage/leave.
Параметры
roomNameStringобязательныйRoom name.
identityStringобязательныйThe co-publisher leaving the stage.
requestStagemethodasyncFuture<Map<String, dynamic>> requestStage({required String roomName, required String identity})A viewer asks to go on stage; the engine notifies host/admins via a _stage_request message (no persisted queue). POST /api/v1/rooms/:name/stage/request.
Параметры
roomNameStringобязательныйRoom name.
identityStringобязательныйThe requesting viewer's identity.
Chat controller
Room chat: send, receive, and retain messages (UTDRoomController.chatController).
sendMessagemethodasyncFuture<void> sendMessage(String text, {Map<String, dynamic>? userData})Sends a chat message (trims and skips empty text), appends it locally, and broadcasts it over the data channel.
Параметры
textStringобязательныйMessage body.
userDataMap<String, dynamic>?По умолчанию = nullOptional sender metadata (e.g. avatar, VIP frame) attached to the message.
addDisplayMessagemethodvoid addDisplayMessage(UTDChatMessage message)Appends a message to the list for display only (e.g. local system notices), without sending it.
Параметры
messageUTDChatMessageобязательныйMessage to append locally.
clearMessagesmethodvoid clearMessages()Clears the retained chat message list.
messagespropertyfinal ValueNotifier<List<UTDChatMessage>> messagesReactive list of retained chat messages (capped at the most recent 300).
Возвращает: ValueNotifier<List<UTDChatMessage>> — Chat history.
Configuration & theming
Room behaviour, layout overrides, video effects, and color tokens.
UTDLiveRoomConfigconstructorconst UTDLiveRoomConfig({bool showControlsBar = true, bool enableMinimize = true, bool autoHostCamera = false, bool frontCameraOnJoin = true, bool mirrorLocalVideo = true, int maxGuestTiles = 3, ..., UTDRoomTheme theme = const UTDRoomTheme(), UTDRoomStrings? strings, ...})Configuration for UTDLiveRoom: shared room behaviour, live video behaviour, theming, section/tile builder overrides, video effects, and user attributes.
Параметры
showControlsBarboolПо умолчанию = trueRender the built-in controls bar.
enableMinimizeboolПо умолчанию = trueAllow minimizing the room to an overlay.
useSpeakerWhenJoiningboolПо умолчанию = trueRoute audio to the speaker on join.
showGoLiveButtonboolПо умолчанию = trueShow the built-in centered Go Live button during host preview.
autoHostCameraboolПо умолчанию = falseHost publishes the camera immediately on connect, skipping self-preview.
frontCameraOnJoinboolПо умолчанию = trueStart on the front camera.
mirrorLocalVideoboolПо умолчанию = trueMirror the local camera tile (selfie view).
maxGuestTilesintПо умолчанию = 3Max simultaneous guest tiles (host excluded); enforced server-side too.
hostFitVideoViewFitПо умолчанию = VideoViewFit.coverHow the host's full-bleed video is fitted.
guestFitVideoViewFitПо умолчанию = VideoViewFit.coverHow each floating guest tile's video is fitted.
themeUTDRoomThemeПо умолчанию = const UTDRoomTheme()Color tokens for the built-in UI.
stringsUTDRoomStrings?По умолчанию = nullLocalized strings; null = English defaults.
headerWidgetWidget?По умолчанию = nullOverride for the room header section.
messagesWidgetWidget?По умолчанию = nullOverride for the chat/messages area.
controlsBarWidgetWidget?По умолчанию = nullOverride for the controls bar.
guestTileFooterBuilderWidget Function(BuildContext, String)?По умолчанию = nullOverlay at the bottom of each guest tile, receives the guest identity.
onStageTapvoid Function()?По умолчанию = nullCalled when the empty host-video stage area is tapped (e.g. tap-hearts).
userInRoomAttributesMap<String, String>По умолчанию = const {}Attributes shared with other participants.
buildVideoProcessorTrackProcessor<VideoProcessorOptions> Function()?По умолчанию = nullFactory building a fresh video-effects (beauty/filter) processor per camera capture.
UTDRoomThemeconstructorconst UTDRoomTheme({Color background, Color surface, Color onSurface, Color primary, Color danger, Color seatRingSpeaking, Color badgeHost, Color badgeAdmin, ...})Color tokens for the package's built-in default UI. Every field has a dark-room default, so const UTDRoomTheme() is a complete, usable theme.
Параметры
backgroundColorПо умолчанию = Color(0xFF14121C)Full-screen room background.
surfaceColorПо умолчанию = Color(0xFF1C1C28)Surface behind grouped content.
onSurfaceColorПо умолчанию = Colors.whitePrimary foreground color for text/icons.
primaryColorПо умолчанию = Color(0xFF6C5CE7)Accent / call-to-action color.
dangerColorПо умолчанию = Color(0xFFE74C3C)Destructive color (leave, kick, ban, mute).
seatRingSpeakingColorПо умолчанию = Color(0xFF2ECC71)Ring around a tile whose occupant is speaking.
badgeHostColorПо умолчанию = Color(0xFFFFA726)Badge color for the host role.
badgeAdminColorПо умолчанию = Color(0xFF448AFF)Badge color for the admin role.
copyWithmethodUTDRoomTheme copyWith({Color? background, Color? surface, Color? primary, Color? danger, ...})Returns a copy of the theme with the given tokens overridden — rebrand without replacing whole widgets.
Models & enums
Data types for participants, seats, roles, bans, chat, and exceptions.
UTDParticipantclassconst UTDParticipant({required String id, required String name, bool isMicEnabled = false, bool isSpeaking = false, Map<String, String> attributes = const {}})A room participant: id, display name, mic/speaking state, and custom attributes (e.g. 'fr' frame, 'frt' frame type, 'cn' color name).
Параметры
idStringобязательныйUnique user ID.
nameStringобязательныйDisplay name.
isMicEnabledboolПо умолчанию = falseWhether the participant's mic is on.
isSpeakingboolПо умолчанию = falseWhether the participant is currently speaking.
attributesMap<String, String>По умолчанию = const {}Custom participant attributes.
UTDRoleenumenum UTDRole { visitor, audience, guest, admin, host }The known engine roles, lowest to highest privilege. The room owner is identified separately (owner_identity), not by these roles.
SeatStateclassconst SeatState({required int index, String? occupantUserId, Map<String, String> attributes = const {}})One tile in the live room: index 0 = host, 1..N = guest tiles. On the wire this is a backend seat.
Параметры
indexintобязательныйTile/seat index (0 = host).
occupantUserIdString?По умолчанию = nullUser occupying the tile; null = empty.
attributesMap<String, String>По умолчанию = const {}Occupant attributes (name, avatar, fr, frt).
UTDRoleChangeEventclassconst UTDRoleChangeEvent({required String identity, required String role, String? previousRole})Realtime _role_change event broadcast to all participants. Server-sent, so identify the affected user from identity (the LiveKit sender is null).
Параметры
identityStringобязательныйAffected user's identity.
roleStringобязательныйNew role.
previousRoleString?По умолчанию = nullRole before the change.
UTDChatMessageclassUTDChatMessage({required String senderUserId, required String senderName, required String text, required DateTime timestamp, Map<String, dynamic> userData = const {}, String? messageID})A chat message. The text field is untrusted, peer-supplied input relayed verbatim — render as plain text only.
Параметры
senderUserIdStringобязательныйSender's identity.
senderNameStringобязательныйSender's display name.
textStringобязательныйMessage body (untrusted plain text).
timestampDateTimeобязательныйWhen the message was created.
userDataMap<String, dynamic>По умолчанию = const {}Optional sender metadata.
messageIDString?По умолчанию = autoMessage id; defaults to a millisecond timestamp string.
UTDBanNoticeclassconst UTDBanNotice({String? roomName, String? reason, DateTime? expiresAt, UTDBanSource source = UTDBanSource.dataMessage})A ban (or forced-exit) notice delivered to the local user, with named constructors for data-message, disconnect, token-403, and signed-in-elsewhere sources.
Параметры
roomNameString?По умолчанию = nullRoom the ban applies to; null = global.
reasonString?По умолчанию = nullBan reason when known.
expiresAtDateTime?По умолчанию = nullExpiry; null = permanent.
sourceUTDBanSourceПо умолчанию = UTDBanSource.dataMessageWhere the notice originated.
UTDBannedExceptionclassconst UTDBannedException([String message = 'User is banned', int statusCode = 403])Thrown by token generation when the server returns 403 User is banned.
Параметры
messageStringПо умолчанию = 'User is banned'Error message.
statusCodeintПо умолчанию = 403HTTP status code.
Готовы создавать вместе с UTD?
Создайте аккаунт, пополните главный кошелёк и включите нужные вам сервисы.