返回开发者中心

< Flutter UIKit />

UTD Audio Room Kit

开箱即用的实时音频房间,内置座位、实时聊天与审核管理。

版本 1.5.0在 pub.dev 上
iOS 11+Android 21+
audio_room_kit.dart
import 'package:utd_audio_room_kit/utd_audio_room_kit.dart';

UTDAudioRoom(
  appId: '<utd-app-id>',
  appKey: '<utd-app-key>',
  userId: 'user123',
  userName: 'John Doe',
  roomId: 'room456',
  roomOwnerId: 'owner789',
);

Drop-in

完整 UI

0

后端服务器

EN · AR

内置多语言

PiP

+ 最小化

< utd_audio_room_kit />

核心功能

一个完整且可定制的 Flutter 套件,用于打造由 LiveKit 与 UTD Stream Engine 驱动的实时音频房间体验。开箱即用的房间 UI,涵盖座位管理、上麦申请、成员列表、实时聊天、媒体控制、最小化/PiP,以及完整的房主/管理员审核管理——无需自建后端令牌服务器。

开箱即用的音频房间 UI——无需额外代码

座位管理:上座、离座、切换、锁定、解锁、踢出、静音、换位

支持通过/拒绝的上麦申请队列

带房主/管理员操作的成员列表(静音、踢出、邀请、封禁、升降级)

通过数据通道的实时聊天,支持批处理与去重

麦克风与扬声器控制,优先采用蓝牙路由

分级重连(轻量同步 <15s,完整同步 <60s)

最小化为悬浮窗及 Android OS 画中画(Picture-in-Picture)

主题定制与内置多语言支持(EN/AR)

整段区块替换(头部、消息、控制栏、背景、座位)

无需后端令牌服务器——基于 appKey 的令牌流程

< utd_audio_room_kit />

开始使用

1

安装

Terminal
flutter pub add utd_audio_room_kit
2

在 pub.dev 上查看

开箱即用的实时音频房间,内置座位、实时聊天与审核管理。

< utd_audio_room_kit />

API 参考

Main widget

The drop-in prebuilt audio-room widget that hosts the full UI and connection lifecycle.

UTDAudioRoomwidget
const UTDAudioRoom({required String appId, required String appKey, required String userId, required String userName, required String roomId, required String roomOwnerId, Set<String> adminIds, UTDAudioRoomConfig config, List<UTDRoomMode> modes, UTDRoomController? controller, ...})

Prebuilt audio-room widget. Mints a token directly from the engine with the publishable appKey (no backend), connects to LiveKit, and renders seats, chat and controls. Self-upgrades admins post-join.

参数

  • appIdString必填

    UTD Stream Engine app ID.

  • appKeyString必填

    Publishable app key (no backend); used to mint tokens via X-App-Key. The server secret never ships.

  • userIdString必填

    Local user identity.

  • userNameString必填

    Local user display name.

  • roomIdString必填

    Room name to join.

  • roomOwnerIdString必填

    Identity of the room owner; the owner joins as host.

  • adminIdsSet<String>默认值 = const {}

    Identities the app treats as admins at join.

  • adminIdsResolverFuture<Set<String>> Function()?默认值 = null

    Async admin-list source; triggers a non-blocking self-upgrade if it lists the local user.

  • adminIdsNowSet<String> Function()?默认值 = null

    Sync admin-list probe used at token time without waiting.

  • layoutModeString默认值 = '3'

    Room mode id selecting the seat layout / seat count.

  • configUTDAudioRoomConfig默认值 = const UTDAudioRoomConfig()

    Behavior, theming and custom-widget configuration.

  • modesList<UTDRoomMode>默认值 = const []

    Custom room modes registered on the controller.

  • controllerUTDRoomController?默认值 = null

    Optional externally-owned controller (e.g. when restoring from minimize).

  • onControllerReadyvoid Function(UTDRoomController)?默认值 = null

    Called once the controller is created/attached.

  • onConnectionChangedvoid Function(bool isConnected)?默认值 = null

    Fired on connect success/failure.

  • onSeatTapvoid Function(int index, SeatState seat)?默认值 = null

    Called when a seat is tapped.

  • onSeatChangedvoid Function(List<SeatState> seats)?默认值 = null

    Called whenever seat state changes.

  • onConnectErrorvoid Function(Object error, StackTrace)?默认值 = null

    Called when the initial connect fails.

Room controller

Top-level controller owning connection, sub-controllers, roles, bans and speaker flows.

UTDRoomControllerconstructor
UTDRoomController()

Creates the controller and its seat, media, chat, minimize and PiP sub-controllers. Usually created internally by UTDAudioRoom.

initApimethod
void initApi({String baseUrl, String tokenBaseUrl, String? appId, required String appKey})

Initializes the engine and token API clients. Must be called before connect/generateToken. Token issuance and in-room ops use different hosts.

参数

  • baseUrlString默认值 = UTDApiClient.defaultBaseUrl

    In-room engine host for seat/speaker/ban/role calls.

  • tokenBaseUrlString默认值 = UTDApiClient.defaultTokenBaseUrl

    Edge host used for token generation.

  • appIdString?默认值 = null

    Engine app ID.

  • appKeyString必填

    Publishable app key sent as X-App-Key for minting.

connectmethodasync
Future<void> connect({required String url, required String token, int seatCount = 9, bool enableMicOnJoin = false, bool useSpeaker = true, Map<String,String> userAttributes, String? roomName})

Connects to the LiveKit room with the given url/token, initializes seats, wires data/role/ban/chat-lock handlers, and optionally enables the mic and speaker.

参数

  • urlString必填

    LiveKit server URL.

  • tokenString必填

    LiveKit access token.

  • seatCountint默认值 = 9

    Number of seats to initialize.

  • enableMicOnJoinbool默认值 = false

    Publish the local mic on connect.

  • useSpeakerbool默认值 = true

    Prefer Bluetooth/loudspeaker output on join.

  • userAttributesMap<String,String>默认值 = const {}

    Cosmetic LiveKit participant attributes (avatar/frame/etc.).

  • roomNameString?默认值 = null

    Room name used for seat API calls.

返回值: Future<void>

generateTokenmethodasync
Future<UTDTokenResponse> generateToken({required String identity, required String roomName, required String roomOwnerId, String role = 'audience', String? name, int? seatCount, String? seatMode, int? hostSeat, String? modeId, ...})

Requests a LiveKit token from the engine and applies the returned per-user bearer to the in-room clients. Throws UTDBannedException on a 403 banned response.

参数

  • identityString必填

    User identity.

  • roomNameString必填

    Room name.

  • roomOwnerIdString必填

    Room owner identity.

  • typeString默认值 = 'audio_room'

    Room type.

  • roleString默认值 = 'audience'

    Requested role (host/admin/audience).

  • nameString?默认值 = null

    Display name.

  • seatCountint?默认值 = null

    Initial seat count (host only).

  • modeIdString?默认值 = null

    Room mode id (host only).

返回值: Future<UTDTokenResponse>

leavemethodasync
Future<void> leave()

Leaves the room: tears down listeners, drains any pending mic publish, disconnects LiveKit, and resets minimize/PiP state.

返回值: Future<void>

changeRolemethodasync
Future<UTDRoleChangeResult> changeRole({required String targetIdentity, required String role})

Changes a participant's role (owner-only; server returns 403 otherwise). Optimistically caches the result; throws on REST error.

参数

  • targetIdentityString必填

    Identity whose role changes.

  • roleString必填

    New role (host/admin/guest/audience).

返回值: Future<UTDRoleChangeResult>

banUsermethodasync
Future<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 and durationSeconds null for permanent. Returns true on success.

参数

  • identityString必填

    User to ban.

  • reasonString?默认值 = null

    Optional ban reason.

  • durationSecondsint?默认值 = null

    Ban duration; null = permanent.

  • globalbool默认值 = false

    True for a project-wide ban.

返回值: Future<bool>

lockCommentsmethodasync
Future<bool> lockComments()

Locks room chat so only host/admin may send (host/admin-only). State is confirmed by the server broadcast, not set optimistically.

返回值: Future<bool>

requestToSpeakmethodasync
Future<Map<String,dynamic>?> requestToSpeak()

Audience requests to speak (request mode). Returns the API result map, or null on error / when not ready.

返回值: Future<Map<String,dynamic>?>

inviteToSpeakmethodasync
Future<Map<String,dynamic>?> inviteToSpeak(String targetIdentity, {int? seatIndex})

Host/admin invites a user to speak, optionally targeting a specific seat. Returns the API result map or null.

参数

  • targetIdentityString必填

    Identity to invite.

  • seatIndexint?默认值 = null

    Target seat the invitee is seated on if accepted.

返回值: Future<Map<String,dynamic>?>

isConnectedgetter
bool get isConnected

True when the room connection state is connected.

返回值: bool

isHostOrAdmingetter
bool get isHostOrAdmin

Whether the local participant's role is host or admin.

返回值: bool

participantsStreamgetterasync
Stream<List<UTDParticipant>> get participantsStream

Stream of all room participants, emitting on join/leave/attribute/metadata changes.

返回值: Stream<List<UTDParticipant>>

roleChangeStreamgetterasync
Stream<UTDRoleChangeEvent> get roleChangeStream

Stream of role changes for all participants (promotions, demotions, engine auto-corrections).

返回值: Stream<UTDRoleChangeEvent>

activeSpeakersproperty
final ValueNotifier<Set<String>> activeSpeakers

Reactive set of identities currently speaking, polled from LiveKit every 300ms.

返回值: ValueNotifier<Set<String>>

commentsLockedproperty
final ValueNotifier<bool> commentsLocked

Reactive whether room chat is currently locked (server-driven; never set optimistically).

返回值: ValueNotifier<bool>

onBannedcallback
void Function(UTDBanNotice notice)? onBanned

Fired once when the local user is banned from any source (data message, removal, or token 403). Wired internally by UTDAudioRoom.

返回值: void Function(UTDBanNotice)?

disposemethod
void dispose()

Releases all resources: timers, subscriptions, notifiers, sub-controllers and API clients.

Seat & stage control

Seat state management; all mutations go through the REST API and apply from server _seat_update messages.

UTDSeatControllerclass
UTDSeatController(UTDRoomManager roomManager)

Manages reactive seat state. Mutations call the REST API; local state updates only from _seat_update data messages or room _seats metadata.

takeSeatmethodasync
Future<bool> takeSeat(int index, String userId)

Requests microphone (and Bluetooth on Android) permissions then takes the seat at index via the API. State arrives via _seat_update.

参数

  • indexint必填

    Target seat index.

  • userIdString必填

    Identity taking the seat.

返回值: Future<bool>

leaveSeatmethodasync
Future<bool> leaveSeat(String userId)

Leaves the user's current seat via the API.

参数

  • userIdString必填

    Identity leaving the seat.

返回值: Future<bool>

moveSeatmethodasync
Future<bool> moveSeat(String userId, int targetSeat)

Atomically moves the user to another seat via the API.

参数

  • userIdString必填

    Identity to move.

  • targetSeatint必填

    Destination seat index.

返回值: Future<bool>

lockSeatmethodasync
Future<bool> lockSeat(int index, {required String identity})

Admin locks the seat at index (host/admin). State arrives via _seat_update.

参数

  • indexint必填

    Seat to lock.

  • identityString必填

    Acting host/admin identity.

返回值: Future<bool>

kickFromSeatmethodasync
Future<bool> kickFromSeat(int index, {required String identity})

Removes the occupant from the seat at index (host/admin only).

参数

  • indexint必填

    Seat to vacate.

  • identityString必填

    Acting host/admin identity.

返回值: Future<bool>

setupSeatsmethodasync
Future<bool> setupSeats({required String identity, required int seatCount, required String seatMode, String? modeId})

Changes seat configuration mid-room (count/mode/modeId) (host/admin only).

参数

  • identityString必填

    Acting host/admin identity.

  • seatCountint必填

    New seat count.

  • seatModeString必填

    New seat mode ('free'/'request').

  • modeIdString?默认值 = null

    New room mode id.

返回值: Future<bool>

seatsproperty
final ValueNotifier<List<SeatState>> seats

Reactive list of all seat states.

返回值: ValueNotifier<List<SeatState>>

pendingRequestsproperty
final ValueNotifier<List<SpeakerRequest>> pendingRequests

Reactive list of pending speaker requests (for host/admin UI).

返回值: ValueNotifier<List<SpeakerRequest>>

getSeatIndexByUserIdmethod
int getSeatIndexByUserId(String userId)

Returns the seat index occupied by a user, or -1 if not seated.

参数

  • userIdString必填

    Identity to look up.

返回值: int

isSeatAvailablemethod
bool isSeatAvailable(int index, {String? userId})

Whether the seat at index is empty, unlocked and not reserved for someone else.

参数

  • indexint必填

    Seat index to test.

  • userIdString?默认值 = null

    User to evaluate reservations against.

返回值: bool

Media control

Mic, camera, speaker and Bluetooth-routing controls, kept in sync with server/host-side mutes.

UTDMediaControllerclass
UTDMediaController(UTDRoomManager roomManager)

Controls mic, camera and speaker state and listens to LiveKit mute/permission events to keep reactive state authoritative.

setMicrophoneEnabledmethodasync
Future<void> setMicrophoneEnabled(bool enabled)

Enables/disables the local mic. Refuses to publish on a non-connected room to avoid the addTransceiver-on-disposed-track crash.

参数

  • enabledbool必填

    Target mic state.

返回值: Future<void>

toggleMicrophonemethodasync
Future<void> toggleMicrophone()

Toggles the local microphone on/off.

返回值: Future<void>

applyBluetoothAudioRoutingmethodasync
Future<void> applyBluetoothAudioRouting()

Re-applies the Android communication audio config with forceHandleAudioRouting so Bluetooth routing works after connect/publish; iOS uses the AVAudioSession path.

返回值: Future<void>

setSpeakerOnmethodasync
Future<void> setSpeakerOn(bool on)

Routes audio to the loudspeaker (true) or earpiece (false).

参数

  • onbool必填

    Speakerphone on/off.

返回值: Future<void>

muteAllRemoteAudiomethod
void muteAllRemoteAudio(bool mute)

Mutes/unmutes playback of all remote participants' audio (and enforces it on late-subscribed tracks).

参数

  • mutebool必填

    Whether to mute remote audio.

isMicEnabledproperty
final ValueNotifier<bool> isMicEnabled

Reactive local mic state, kept in sync with LiveKit track mute/unmute events.

返回值: ValueNotifier<bool>

canPublishproperty
final ValueNotifier<bool> canPublish

Reactive whether the local participant may publish mic/camera; flips false on demotion.

返回值: ValueNotifier<bool>

Chat

Room chat send/receive with comment-lock gating and a bounded message buffer.

UTDChatControllerclass
UTDChatController(UTDRoomManager roomManager)

Sends and receives room chat over the data channel, enforcing the comment-lock gate and capping retained messages at 300.

sendMessagemethodasync
Future<void> sendMessage(String text, {Map<String,dynamic>? userData})

Sends a chat message (trimmed, non-empty). Refused when comments are locked and the local user is not host/admin.

参数

  • textString必填

    Message body.

  • userDataMap<String,dynamic>?默认值 = null

    Optional extra payload attached to the message.

返回值: Future<void>

addDisplayMessagemethod
void addDisplayMessage(UTDChatMessage message)

Appends a message to the local list without sending it (used for system lines).

参数

  • messageUTDChatMessage必填

    Message to display locally.

clearMessagesmethod
void clearMessages()

Clears the local message list.

messagesproperty
final ValueNotifier<List<UTDChatMessage>> messages

Reactive list of chat messages (bounded to the most recent 300).

返回值: ValueNotifier<List<UTDChatMessage>>

Configuration & theming

Behavior config, color tokens, localized strings and minimize/PiP options.

UTDAudioRoomConfigconstructor
const UTDAudioRoomConfig({bool showControlsBar = true, bool turnOnMicrophoneWhenJoining = false, bool useSpeakerWhenJoining = true, int hostSeatIndex = 0, UTDRoomTheme theme, UTDRoomStrings? strings, bool enableMinimize = true, Widget? headerWidget, ...})

Configures room behavior, theme, strings and custom section/seat builders. Replaces the prebuilt config.

参数

  • showControlsBarbool默认值 = true

    Show the default controls bar.

  • showSeatNamesbool默认值 = true

    Show occupant names under seats.

  • enableMinimizebool默认值 = true

    Allow minimizing the room to a floating overlay.

  • turnOnMicrophoneWhenJoiningbool默认值 = false

    Publish the mic on join.

  • useSpeakerWhenJoiningbool默认值 = true

    Prefer speaker/Bluetooth output on join.

  • hostSeatIndexint默认值 = 0

    Seat index reserved for the host.

  • themeUTDRoomTheme默认值 = const UTDRoomTheme()

    Color tokens for the default UI.

  • stringsUTDRoomStrings?默认值 = null

    Localized strings; null = English defaults.

  • autoHostMicbool默认值 = true

    Auto-enable the host's mic even if join-mic is false.

  • autoSeatHostbool默认值 = true

    Auto-seat the host on hostSeatIndex if empty.

  • headerWidgetWidget?默认值 = null

    Custom header replacing the default.

  • seatBuilderWidget Function(SeatState, double)?默认值 = null

    Custom builder for a seat slot.

  • avatarBuilderWidget Function(String,double,Map<String,String>,bool,int,String)?默认值 = null

    Custom occupant avatar builder.

  • userInRoomAttributesMap<String,String>默认值 = const {}

    Cosmetic attributes published to other participants.

UTDAudioRoomConfig.hostconstructor
factory UTDAudioRoomConfig.host()

Factory preset for a host (microphone on when joining).

resolveStringsmethod
UTDRoomStrings resolveStrings()

Returns the configured strings or the English defaults.

返回值: UTDRoomStrings

UTDRoomThemeconstructor
const UTDRoomTheme({Color background, Color surface, Color onSurface, Color primary, Color danger, Color seatRingSpeaking, Color badgeHost, Color badgeAdmin, Color badgeGuest, Color sheetBackground, Color bubbleBackground, ...})

Color tokens for the built-in default UI. Every field has a dark-room default, so const UTDRoomTheme() is a complete theme.

参数

  • backgroundColor默认值 = Color(0xFF14121C)

    Full-screen room background.

  • primaryColor默认值 = Color(0xFF6C5CE7)

    Accent / call-to-action color.

  • dangerColor默认值 = Color(0xFFE74C3C)

    Destructive color (leave/kick/ban).

  • seatRingSpeakingColor默认值 = Color(0xFF2ECC71)

    Ring around an actively-speaking seat.

  • badgeHostColor默认值 = Color(0xFFFFA726)

    Host role badge color.

  • badgeAdminColor默认值 = Color(0xFF448AFF)

    Admin role badge color.

copyWithmethod
UTDRoomTheme copyWith({Color? background, Color? primary, Color? danger, ...})

Returns a copy of the theme overriding only the supplied color tokens.

返回值: UTDRoomTheme

UTDRoomStrings.enconstructor
factory UTDRoomStrings.en()

English defaults for all built-in UI labels (seat actions, requests, host panels, comment-lock, templated lines).

UTDRoomStrings.arconstructor
factory UTDRoomStrings.ar()

Arabic defaults for all built-in UI labels.

UTDMinimizeConfigconstructor
const UTDMinimizeConfig({VoidCallback? onClose, MiniOverlayBuilder? overlayBuilder, double overlayWidth = 120, double overlayHeight = 120, bool enableOSPip = false, int pipAspectWidth = 1, int pipAspectHeight = 1, ...})

Configures the minimize floating overlay and optional Android OS-level Picture-in-Picture (enableOSPip).

参数

  • onCloseVoidCallback?默认值 = null

    Called when the room is closed from the overlay.

  • overlayBuilderMiniOverlayBuilder?默认值 = null

    Custom floating-overlay builder.

  • enableOSPipbool默认值 = false

    Enable Android 12+ system PiP in addition to the overlay.

  • pipAspectWidthint默认值 = 1

    PiP aspect ratio numerator.

  • pipAspectHeightint默认值 = 1

    PiP aspect ratio denominator.

Models & enums

Data models for seats, room modes, chat and connection state.

SeatStateclass
const SeatState({required int index, String? occupantUserId, bool isLocked = false, bool isMuted = false, String? reservedFor, Map<String,String> attributes})

Immutable (Equatable) state of a single seat: index, occupant, lock/mute flags, reservation and occupant attributes.

参数

  • indexint必填

    Seat index (0 = host seat).

  • occupantUserIdString?默认值 = null

    Occupant identity; null = empty.

  • isLockedbool默认值 = false

    Whether the seat is admin-locked.

  • isMutedbool默认值 = false

    Whether the occupant's mic is muted.

  • reservedForString?默认值 = null

    Identity this seat is reserved for.

  • attributesMap<String,String>默认值 = const {}

    Occupant cosmetic attributes (avatar, frame, etc.).

SpeakerRequestclass
const SpeakerRequest({required int id, required String identity, String? createdAt})

A pending request to speak: id, requester identity and createdAt timestamp.

参数

  • idint必填

    Request id.

  • identityString必填

    Requesting identity.

  • createdAtString?默认值 = null

    Creation timestamp.

RoomSeatStateclass
const RoomSeatState({required int count, required String mode, String? modeId, required List<SeatState> seats, required List<SpeakerRequest> requests})

Full seat snapshot from the backend _seats namespace: count, mode, modeId, seats and pending requests.

参数

  • countint必填

    Seat count.

  • modeString必填

    Seat mode ('free'/'request').

  • modeIdString?默认值 = null

    Room mode id.

  • seatsList<SeatState>必填

    Per-seat states.

  • requestsList<SpeakerRequest>必填

    Pending speaker requests.

UTDRoomModeclass
const UTDRoomMode({required String id, required int seatCount, required List<List<int>> rows, double? seatSize, UTDSeatContainerBuilder? containerBuilder, UTDBackgroundBuilder? backgroundBuilder, String? displayName})

Defines a seat layout mode: id, seat count, row arrangement and optional custom container/background builders. Identity is its id.

参数

  • idString必填

    Unique mode id (e.g. '3').

  • seatCountint必填

    Number of seats.

  • rowsList<List<int>>必填

    Seat-index layout per row.

  • seatSizedouble?默认值 = null

    Explicit seat size override.

  • containerBuilderUTDSeatContainerBuilder?默认值 = null

    Custom seat-grid container builder.

  • backgroundBuilderUTDBackgroundBuilder?默认值 = null

    Mode-specific background builder.

computeSeatSizemethod
double computeSeatSize(double screenWidth)

Single source of truth for the seat slot size in logical px, scaled sub-linearly (sqrt) with screen width and clamped to 52–120.

参数

  • screenWidthdouble必填

    Available screen width.

返回值: double

UTDRoomMode.defaultModefield
static const UTDRoomMode defaultMode

Built-in default mode: id '3', 9 seats in a 1-4-4 layout.

返回值: UTDRoomMode

UTDChatMessageclass
UTDChatMessage({required String senderUserId, required String senderName, required String text, required DateTime timestamp, Map<String,dynamic> userData, String? messageID})

A chat message with sender, text, timestamp, arbitrary userData and an auto-generated messageID. JSON-serializable.

参数

  • senderUserIdString必填

    Sender identity.

  • senderNameString必填

    Sender display name.

  • textString必填

    Message body.

  • timestampDateTime必填

    Message time.

  • userDataMap<String,dynamic>默认值 = const {}

    Extra payload (e.g. system-line markers).

  • messageIDString?默认值 = null

    Message id; auto-generated when omitted.

UTDConnectionStateenum
enum UTDConnectionState { disconnected, connecting, connected, reconnecting, error }

Room connection state: disconnected, connecting, connected, reconnecting, error.

返回值: UTDConnectionState

准备好与 UTD 一起构建了吗?

创建账户,为主钱包充值,按需开启你所需要的服务。