dart_plex 0.3.0
dart_plex: ^0.3.0 copied to clipboard
Dart client for Plex Media Server and plex.tv. Supports JWT sign-in, library browsing, playlists, streaming, search and more, on Android, iOS, Linux, macOS, Windows and the web.
dart_plex #
Plex Media Server client for Flutter and Dart.
![]() |
dart_plex is a Dart client for Plex Media Server 1.43. It covers libraries, playlists, streaming, playback reporting, play queues and search through typed Dart objects, and handles plex.tv sign-in and server discovery. |
Installation #
It needs Dart 3.10 or later, and is tested against Plex Media Server 1.43.2.
Add dart_plex to your pubspec.yaml:
dependencies:
dart_plex: ^0.3.0
Features #
| Pure Dart no native plugin and no Flutter dependency. The main library also runs on the web; only the file helpers in io.dart need dart:io. |
Typed models libraries, items, media, streams, hubs, server info, history and events are typed Dart objects, each with a raw map for the fields it does not lift. |
||
| JWT sign-in an Ed25519 device key and 7-day plex.tv tokens the client refreshes on its own, with the legacy PIN and password flows still there. |
Server discoveryfetchResources() lists owned and shared servers; connectToResource() tries every connection at once and takes the best that answers, IPv6 included. |
||
| One client a PlexClient holds the identity, the server and the token, and every sub-API works through it. |
StreamingstartAudioTranscode() and startVideoTranscode() make the decision and return the URL; directFileUrl() gives the original file. |
||
| Any HTTP stack built on package:http: pass a CupertinoClient or CronetClient for HTTP/2 and the system proxy, or a MockClient in tests (see Client and sign-in). |
Off the caller's isolate large answers are inflated, decoded and parsed into models on a background isolate, so the UI keeps its frames. |
||
Cancellation and retrieswithCancelToken() makes every call of a view cancellable, and an opt-in PlexRetryPolicy resends idempotent requests after transient failures. |
Live events the server's notifications decoded into a sealed PlexEvent type: play states, library changes, scans. |
||
| Typed errors every failure is a PlexException with a type to branch on: auth, pass required, not found, network, transient, cancelled. |
Escape hatchrequest(), requestBytes() and requestStream() for endpoints the sub-APIs do not cover. |
Quick start #
import 'package:dart_plex/dart_plex.dart';
Future<void> main() async {
final plex = PlexClient(
credentials: const PlexCredentials(
clientIdentifier: 'PUT-YOUR-UUID-HERE', // stable per install
product: 'MyApp',
version: '1.0.0',
device: 'iPhone',
deviceName: 'My iPhone',
platform: 'iOS',
),
);
// 1. Sign in with a device key: the user approves the PIN in a browser.
final key = await PlexDeviceKey.generate(); // persist it, see Client and sign-in
var pin = await plex.account.createJwtPin(key: key);
print('Sign in at ${plex.account.authAppUrl(pin)}');
while (!pin.isAuthenticated) {
await Future<void>.delayed(const Duration(seconds: 1));
pin = await plex.account.pollJwtPin(id: pin.id, key: key);
}
// The JWT lasts 7 days; the client refreshes it with the key.
await plex.useJwt(
PlexJwtSession(key: key, token: PlexJwt.parse(pin.authToken!)),
);
// 2. Find the user's server and connect through the best connection
// that answers.
final servers = await plex.account.fetchResources();
final server = servers.firstWhere((s) => s.owned);
await plex.connectToResource(server);
// 3. Browse the music library.
final sections = await plex.library.sections();
final music = sections.firstWhere((s) => s.type == PlexLibraryType.music);
final albums = await plex.library.allByType(
sectionId: music.id,
type: PlexMetadataType.album,
sort: PlexSort.titleSort.asc,
);
// 4. Stream the first track of the first album.
final tracks =
await plex.library.children(ratingKey: albums.items.first.ratingKey);
final transcode = await plex.streaming.startAudioTranscode(
ratingKey: tracks.first.ratingKey,
session: 'a-uuid-per-playback',
maxAudioBitrateKbps: 192,
);
print(transcode.url); // hand this to your audio engine
// 5. Release the HTTP client.
plex.close();
}
How it works #
PlexClient holds the identity of your app, the server and the token. Each part of the Plex API is a sub-API on it (plex.library, plex.playlists, plex.streaming and so on), and every call goes through one connection, the same transport dart_jellyfin uses.
Working with the client #
A client for tests #
final plex = PlexClient(
credentials: credentials,
httpClient: MockClient((request) async => http.Response(
'{"MediaContainer":{"size":0,"Directory":[]}}',
200,
headers: {'content-type': 'application/json'},
)),
);
Any http.Client works, such as cupertino_http or cronet_http for HTTP/2 and the system proxy. See Client and sign-in for the constructor options, credentials, both sign-in flows and how a connection is picked.
The server #
final info = await plex.server.info();
print('${info.friendlyName} ${info.version}, sonic analysis: ${info.musicAnalysis}');
final running = await plex.activities.list();
final scan = running.where((a) => a.cancellable).firstOrNull;
if (scan != null) await plex.activities.cancel(activityId: scan.uuid);
See Server for butler tasks, settings, the log, updates and the other admin calls.
Filtered browsing #
final page = await plex.library.allByType(
sectionId: music.id,
type: PlexMetadataType.album,
filters: [PlexFilter.genre(6), PlexFilter.yearAfter(2009)],
sort: PlexSort.addedAt.desc,
);
print('Got ${page.items.length} of ${page.totalSize}');
See Library for sections, filters, facets, collections, editing and sonic radio.
Reporting a play #
await plex.playback.timeline(
ratingKey: track.ratingKey,
playState: PlexPlayState.playing,
timeMs: 42000,
durationMs: track.durationMs!,
);
Send a report on every state change and every 10 s while playing. See Playback and play queues for when a play counts, ratings, sessions, history and server play queues.
A playlist #
final playlist = await plex.playlists.create(
title: 'My Mix',
type: PlexMediaType.audio,
machineIdentifier: machineId,
itemRatingKeys: const ['12345', '12346'],
);
See Playlists for listing, editing entries, smart playlists and import.
A transcode to keep alive #
final transcode = await plex.streaming.startAudioTranscode(
ratingKey: track.ratingKey,
session: sessionId,
maxAudioBitrateKbps: 128,
);
await plex.streaming.pingUniversal(session: sessionId); // every 30 s while paused
await plex.streaming.stopUniversal(session: sessionId); // when the user leaves
The calls return URLs and never fetch the audio. See Streaming for video transcodes over HLS, DASH or HTTP, the remote-streaming pass, direct files, transcoder URLs, lyrics and loudness.
Live TV #
final dvrs = await plex.liveTv.dvrs();
await plex.dvrs.tuneChannel(dvrId: dvrId, channel: '2.1');
final rules = await plex.subscriptions.list();
The answers are typed (PlexDvr, PlexMediaSubscription, …). See Live TV for sessions, DVRs, recording rules, tuners and the program guide.
Errors #
try {
await plex.library.sections();
} on PlexException catch (e) {
if (e.isPassRequired) showPassNeeded(); // remote video needs a pass
else if (e.isAuthError) await signInAgain();
else if (e.isTransient) scheduleRetry(e.retryAfter);
else showError(e.message);
}
See Errors and paging for the error types, cancel tokens, the retry policy and paging. Raw requests reach the endpoints the sub-APIs do not cover.
Search as you type #
searchToken?.cancel(); // drop the previous keystroke's request
final token = searchToken = PlexCancelToken();
final hubs = await plex.withCancelToken(token).search.hubs(query: text);
See Search for hub, section, flat and voice search.
Live events #
final frames = await plex.notifications.connectWebSocket();
frames.events().listen((event) {
if (event is PlexActivityEvent && event.isLibraryScan && event.isEnded) {
reloadLibrary();
}
});
See Events and downloads for every event type and for downloads to disk.
Artwork #
final url = plex.images.transcodeUrl(sourcePath: album.thumb!, width: 300, height: 300);
final cacheKey = '${album.ratingKey}@${album.thumbVersion}';
See Images and hubs for artwork versions, UltraBlur backdrops and the home screen's hubs.
Documentation #
- API reference, with these guides:
- Client and sign-in: the client, credentials, the HTTP stack, tests, JWT and PIN sign-in, Plex Home, the watchlist and connecting to a server
- Server: identity, activities, butler tasks, settings and administration
- Library: sections, items, filters, collections, editing and sonic radio
- Playlists: listing, creating and editing playlists, smart playlists and import
- Search: hub, section, flat and voice search
- Playback and play queues: timeline reports, ratings, sessions, history and play queues
- Streaming: audio and video transcodes, the remote-streaming pass, direct files, lyrics and loudness
- Images and hubs: resized artwork, cache keys, UltraBlur and hubs
- Live TV: live sessions, DVRs, recording rules, tuners and the guide
- Errors and paging: typed errors, cancellation, retries and paging
- Events and downloads: notifications, typed events, downloads and download queues
- Raw requests:
request(),requestBytes()andrequestStream()
- Example
- CHANGELOG and MIGRATION
Project background #
I wrote the typed models, the sub-APIs and the transport with Claude Code.
Plex is a trademark of Plex, Inc. dart_plex is not affiliated with it.
Developed by Alessandro Di Ronza
