titli_video_sdk 0.2.0
titli_video_sdk: ^0.2.0 copied to clipboard
Titli Video SDK for Flutter. Metered 1:1 audio and video calls, Live Hosts, live stream viewing and gifts in your app.
// Titli Video SDK example.
//
// Quick mode (default): only the App Key from the console (Projects > Quick mode), no backend.
//
// flutter run -d chrome \
// --dart-define=TITLI_APP_KEY=tak_... \
// --dart-define=TITLI_USER_ID=user-42 \
// --dart-define=TITLI_API_BASE=https://dev-api-videosdk.titliapp.com (optional, production by default)
// --dart-define=TITLI_CALL_ID=... (optional: join this call)
//
// With an App Key and a user id the app starts at once: it joins TITLI_CALL_ID when given, else it starts a new
// call and shows "Call ID: <id>" so the other side can join with it. Without them it shows a form.
// On web the query string overrides the defines: ?user_id=user-b&call_id=<id> (also app_key, api_base, user_name,
// audio=1), so one build serves both sides.
//
// Secure mode (production hardening): your backend holds the API key secret, creates the call and mints the token
// (POST /v1/calls, POST /v1/calls/{id}/tokens); the app joins with TitliCall.connect. See the "Secure mode" tab.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:http/http.dart' as http;
import 'package:titli_video_sdk/titli_video_sdk.dart';
const appKeyDefine = String.fromEnvironment('TITLI_APP_KEY');
const apiBaseDefine = String.fromEnvironment('TITLI_API_BASE', defaultValue: 'https://api-videosdk.titliapp.com');
const userIdDefine = String.fromEnvironment('TITLI_USER_ID');
const userNameDefine = String.fromEnvironment('TITLI_USER_NAME');
const callIdDefine = String.fromEnvironment('TITLI_CALL_ID');
const audioOnlyDefine = bool.fromEnvironment('TITLI_AUDIO');
/// On web the page's query string can override each define, so one build serves both sides of a call:
/// `?user_id=user-b&call_id=<id>` (also `app_key`, `api_base`, `user_name`, `audio=1`).
String _param(String name, String fallback) {
final v = kIsWeb ? Uri.base.queryParameters[name] : null;
return (v == null || v.isEmpty) ? fallback : v;
}
final appKeyValue = _param('app_key', appKeyDefine);
final apiBaseValue = _param('api_base', apiBaseDefine);
final userIdValue = _param('user_id', userIdDefine);
final userNameValue = _param('user_name', userNameDefine);
final callIdValue = _param('call_id', callIdDefine);
final audioOnlyValue = _param('audio', audioOnlyDefine ? '1' : '') == '1';
/// Secure mode: replace with your own backend endpoint that returns `{ token, livekit_url }` for the signed-in user.
const yourBackend = 'https://your-backend.example.com/calls/start';
/// Secure mode gifts (optional): your backend relays the gift list from `GET /v1/gifts` and sends gifts with its API
/// key. Leave empty to run without gifts; the gift button then stays hidden. (Quick mode needs none of this.)
const yourGiftsEndpoint = ''; // e.g. https://your-backend.example.com/gifts
const yourSendGiftEndpoint = ''; // e.g. https://your-backend.example.com/calls/CALL_ID/gifts
Future<(int, Object?)> _backend(String method, String url, [Object? body]) async {
final req = http.Request(method, Uri.parse(url))..headers['Content-Type'] = 'application/json';
if (body != null) req.body = jsonEncode(body);
final res = await http.Response.fromStream(await req.send());
return (res.statusCode, res.body.isEmpty ? null : jsonDecode(res.body));
}
/// Secure mode: posts gift_id, count, client_request_id and expected_price to your backend. A refusal becomes a
/// TitliGiftError whose userMessage the gift sheet shows.
Future<Object?> sendGift(TitliGiftRequest request) async {
final (status, body) = await _backend('POST', yourSendGiftEndpoint, request.toJson());
if (status >= 400) throw TitliGiftError.fromJson(body, status: status);
return body;
}
/// One line on the console per step, for automated runs (`TITLI_E2E key=value`).
void _e2e(String key, Object? value) => debugPrint('TITLI_E2E $key=$value');
void main() {
WidgetsFlutterBinding.ensureInitialized();
// On web this puts the texts in the page (accessibility tree), so a browser test can read "Call ID: ...".
if (kIsWeb) SemanticsBinding.instance.ensureSemantics();
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Titli Video SDK example',
theme: ThemeData(colorSchemeSeed: const Color(0xFF6D4AFF), useMaterial3: true),
home: const DefaultTabController(length: 2, child: HomePage()),
);
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Titli Video SDK'),
bottom: const TabBar(tabs: [Tab(text: 'Quick mode'), Tab(text: 'Secure mode')]),
),
body: const TabBarView(physics: NeverScrollableScrollPhysics(), children: [QuickModePage(), SecureModePage()]),
);
}
/// The call id as plain text `Call ID: <id>`, found by key `callIdText` (and by the semantics identifier
/// `callIdText` on web).
class CallIdText extends StatelessWidget {
const CallIdText(this.callId, {super.key, this.color});
final String callId;
final Color? color;
@override
Widget build(BuildContext context) => Semantics(
identifier: 'callIdText',
container: true,
child: Text('Call ID: $callId', key: const Key('callIdText'), style: TextStyle(fontWeight: FontWeight.w600, color: color)),
);
}
// ---------------------------------------------------------------------------------------------------------------
// Quick mode
// ---------------------------------------------------------------------------------------------------------------
class QuickModePage extends StatefulWidget {
const QuickModePage({super.key});
@override
State<QuickModePage> createState() => _QuickModePageState();
}
class _QuickModePageState extends State<QuickModePage> with AutomaticKeepAliveClientMixin {
final _appKey = TextEditingController(text: appKeyValue);
final _apiBase = TextEditingController(text: apiBaseValue);
final _userId = TextEditingController(text: userIdValue);
final _userName = TextEditingController(text: userNameValue);
final _callId = TextEditingController(text: callIdValue);
bool _video = !audioOnlyValue;
bool _busy = false;
String _status = 'idle';
String? _error;
String? _shownCallId;
TitliCall? _call;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
_callId.addListener(() => setState(() {}));
if (appKeyValue.isNotEmpty && userIdValue.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) => _go());
}
}
void _setStatus(String s) {
_e2e('status', s);
if (mounted) setState(() => _status = s);
}
Future<void> _go() async {
if (_busy) return;
setState(() {
_busy = true;
_error = null;
});
try {
_setStatus('init');
await TitliVideo.init(
appKey: _appKey.text.trim(),
userId: _userId.text.trim(),
userName: _userName.text.trim().isEmpty ? null : _userName.text.trim(),
apiBase: _apiBase.text.trim().isEmpty ? 'https://api-videosdk.titliapp.com' : _apiBase.text.trim(),
);
final join = _callId.text.trim();
_setStatus(join.isEmpty ? 'starting' : 'joining');
final call = join.isEmpty
? await TitliVideo.startCall(type: _video ? TitliCallType.video : TitliCallType.audio)
: await TitliVideo.joinCall(join);
_e2e('call_id', call.callId);
call.participants.addListener(() => _e2e('participants', call.participants.value.length));
setState(() {
_call = call;
_shownCallId = call.callId;
});
_setStatus('connected');
} on TitliVideoError catch (e) {
_e2e('error', '${e.errorCode} ${e.userCode ?? ''} ${e.message}');
setState(() => _error = e.userMessage ?? '${e.message} (${e.userCode ?? e.errorCode})'); // userMessage already names its code
_setStatus('error');
} catch (e) {
_e2e('error', e);
setState(() => _error = 'Could not connect: $e');
_setStatus('error');
} finally {
if (mounted) setState(() => _busy = false);
}
}
void _onEnded(TitliCallEndReason reason) {
_setStatus('ended ${reason.name}');
// Back to the form after this frame; the call screen disposes the call.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _call = null);
});
}
@override
Widget build(BuildContext context) {
super.build(context);
final call = _call;
if (call != null) {
return Stack(children: [
Positioned.fill(child: TitliCallScreen(call: call, title: 'Quick mode call', onEnded: _onEnded)),
Positioned(
left: 12,
right: 12,
bottom: 120,
child: Center(
child: DecoratedBox(
decoration: BoxDecoration(color: Colors.black54, borderRadius: BorderRadius.circular(8)),
child: Padding(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), child: CallIdText(call.callId ?? '', color: Colors.white)),
),
),
),
]);
}
return ListView(
padding: const EdgeInsets.all(16),
children: [
const Text('Add your App Key and a user id, then start a call. Share the call id with the other person; '
'they paste it under "Call ID" and join.'),
const SizedBox(height: 12),
TextField(controller: _appKey, decoration: const InputDecoration(labelText: 'App Key (tak_...)')),
TextField(controller: _userId, decoration: const InputDecoration(labelText: 'Your user id (e.g. user-42)')),
TextField(controller: _userName, decoration: const InputDecoration(labelText: 'Your name (optional)')),
TextField(controller: _apiBase, decoration: const InputDecoration(labelText: 'API base')),
TextField(controller: _callId, decoration: const InputDecoration(labelText: 'Call ID to join (empty = start a new call)')),
SwitchListTile(title: const Text('Video call'), value: _video, onChanged: (v) => setState(() => _video = v)),
const SizedBox(height: 8),
FilledButton(onPressed: _busy ? null : _go, child: Text(_callId.text.trim().isEmpty ? 'Start call' : 'Join call')),
const SizedBox(height: 12),
Semantics(identifier: 'statusText', container: true, child: Text('Status: $_status', key: const Key('statusText'))),
if (_shownCallId != null) Padding(padding: const EdgeInsets.only(top: 8), child: CallIdText(_shownCallId!)),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Semantics(identifier: 'errorText', container: true, child: Text(_error!, key: const Key('errorText'), style: const TextStyle(color: Colors.red))),
),
],
);
}
}
// ---------------------------------------------------------------------------------------------------------------
// Secure mode (production hardening): the token comes from YOUR backend
// ---------------------------------------------------------------------------------------------------------------
class SecureModePage extends StatefulWidget {
const SecureModePage({super.key});
@override
State<SecureModePage> createState() => _SecureModePageState();
}
class _SecureModePageState extends State<SecureModePage> with AutomaticKeepAliveClientMixin {
final _url = TextEditingController();
final _token = TextEditingController();
bool _video = true;
bool _busy = false;
String? _error;
@override
bool get wantKeepAlive => true;
Future<void> _fetchFromBackend() async {
setState(() => _busy = true);
try {
final (_, body) = await _backend('POST', yourBackend, {'host_id': 'host_42', 'type': _video ? 'video' : 'audio'});
final m = body as Map<String, dynamic>;
_url.text = m['livekit_url'] as String;
_token.text = m['token'] as String;
} catch (e) {
setState(() => _error = 'Could not reach your backend: $e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
Future<void> _join() async {
setState(() {
_busy = true;
_error = null;
});
try {
final gifts = yourGiftsEndpoint.isEmpty ? null : (await _backend('GET', yourGiftsEndpoint)).$2;
final call = await TitliCall.connect(
url: _url.text.trim(),
token: _token.text.trim(),
video: _video,
giftCatalog: gifts,
onSendGift: yourSendGiftEndpoint.isEmpty ? null : sendGift,
onLiveEvent: (e) {
if (e is TitliLiveGiftEvent) debugPrint('gift sent: ${e.gift.count} x ${e.gift.name} (${e.gift.animationUrl})');
},
);
if (!mounted) return;
await Navigator.of(context).push(MaterialPageRoute<void>(
builder: (_) => TitliCallScreen(
call: call,
title: 'Test call',
onEnded: (reason) => debugPrint('call ended: $reason'),
),
));
} catch (e) {
setState(() => _error = 'Could not join: $e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return ListView(
padding: const EdgeInsets.all(16),
children: [
const Text('Your backend keeps the API key secret, creates the call and mints a token for this user.'),
SwitchListTile(title: const Text('Video call'), value: _video, onChanged: (v) => setState(() => _video = v)),
OutlinedButton(onPressed: _busy ? null : _fetchFromBackend, child: const Text('Get a token from my backend')),
const SizedBox(height: 12),
TextField(controller: _url, decoration: const InputDecoration(labelText: 'livekit_url from the API')),
TextField(controller: _token, decoration: const InputDecoration(labelText: 'Participant token'), maxLines: 3),
const SizedBox(height: 16),
FilledButton(onPressed: _busy ? null : _join, child: const Text('Join call')),
if (_error != null) Padding(padding: const EdgeInsets.only(top: 12), child: Text(_error!, style: const TextStyle(color: Colors.red))),
],
);
}
}