Home/docs/guide/Flutter integration

Flutter integration

Flutter Embedding

erika_flutter is the official Flutter plugin for liberika. It supports macOS, iOS, tvOS, Windows, Android, and OpenHarmony, and ships an experimental Linux plugin. It provides full playback control, multi-track management, danmaku and subtitle rendering, ArtCNN upscaling, and three view widgets.

Dependencies and installation#

pubspec.yaml

dependencies:
  erika_flutter: ^0.3.8

Linux x64 / ARM64 offers bundled and system packages. Flutter hosts extract the chosen package and set ERIKA_LIBRARY_DIR, or build from source. Linux integration and PIC setup

Run flutter pub get. Apple, Windows, Android and OpenHarmony builds download the matching native library automatically. On Linux, extract a release package or build from source, then set ERIKA_LIBRARY_DIR. Set ERIKA_FORCE_SOURCE_BUILD=1 and ERIKA_REPO_ROOT to force a source build. The macOS plugin inside the liberika repository detects and builds the local core by default; ERIKA_FORCE_PREBUILT=1 selects a prebuilt package.

Choosing a view#

The plugin provides three rendering view widgets:

View widgetUnderlying mechanismRecommended for
ErikaWindowOverlayVideoViewNative child window / native overlay layerNative presentation on Apple and Windows. On Linux Wayland it uses the native video layer, and the video area must stay transparent.
ErikaTextureVideoViewFlutter Texture: macOS uses IOSurface + Metal, Windows uses a shared D3D11 texture, OpenHarmony uses an external texture, and Linux uses RGBA readback. Other platforms fall back to ErikaVideoView.Use it on macOS / Windows / OpenHarmony / Linux when you need Flutter compositing effects such as Opacity, clipping, transforms, and color filters.
ErikaVideoViewUnified cross-platform view: PlatformView on macOS/iOS, a native window on Windows, TextureView/SurfaceView on Android, an external texture on OpenHarmony, and an RGBA texture on Linux.General-purpose entry point. If you need Flutter clipping or color filters, prefer Texture; Windows Texture outputs SDR.

Basic usage example

import 'package:flutter/material.dart';
import 'package:erika_flutter/erika_flutter.dart';

class VideoScreen extends StatefulWidget {
  const VideoScreen({super.key});

  @override
  State<VideoScreen> createState() => _VideoScreenState();
}

class _VideoScreenState extends State<VideoScreen> {
  final _player = ErikaPlayer();

  @override
  void initState() {
    super.initState();
    _initPlayer();
  }

  Future<void> _initPlayer() async {
    /* 1. Open the media synchronously (parses tracks and duration; state becomes Ready) */
    await _player.open(
      'https://example.com/movie.mp4',
      httpHeaders: {'User-Agent': 'FlutterApp/1.0'},
    );
    /* 2. Start asynchronous decoding and playback */
    await _player.play();
  }

  @override
  void dispose() {
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: ErikaVideoView(player: _player),
        ),
      ),
    );
  }
}

Transparent video and blend modes#

Transparent video is requested per player. ErikaVideoAlphaMode.packedAlphaRight expects side-by-side encoded material: color in the left half and a grayscale alpha mask in the right half. The GPU presentation shaders (Metal / wgpu / D3D11) reconstruct a premultiplied-alpha picture, and the video is presented at half the encoded width. A player that does not request this mode still interprets the picture as opaque, so existing content is unaffected. Blend mode and opacity are passed on the video widget.

Transparent video example

final player = ErikaPlayer(
  videoAlphaMode: ErikaVideoAlphaMode.packedAlphaRight,
);

ErikaTextureVideoView(
  player: player,
  blendMode: BlendMode.overlay,
  opacity: 0.8,
)
Platform and pathblendModeopacity
macOS · ErikaTextureVideoView (Flutter Texture)srcOver only; other values switch to the native layer, where Core Animation blendsFlutter Opacity
macOS · Native layer (blendMode ≠ srcOver)Supports overlay (background-aware); other values are ignoredNative CALayer opacity
Windows · ErikaTextureVideoView (SDR)srcOver; overlay switches to the native composition layerFlutter Opacity
Linux · Flutter texture / Wayland native layerTexture uses Flutter compositing; the native layer supports only opaque srcOverTexture supports Flutter Opacity; the native layer is always opaque
Windows · Window overlay (DirectComposition)srcOver / overlay; other values throw a plugin errorIDCompositionEffectGroup opacity
Android / iOS / OpenHarmonyAccepts the creation parameters but ignores themOn the Texture path, Flutter applies it

Transparent and overlay video in a Windows window overlay no longer uses a separate opaque pop-up window. It composites directly through a premultiplied-alpha DirectComposition swap chain bound to the Flutter HWND, so the Flutter or game content underneath stays visible. HDR sources are tone-mapped inside liberika into that SDR composition space. Opaque video keeps the original child-HWND path.

API overview#

CategoryMethods / propertiesDescription
Playback controlsopen / play / pause / stop / close / seek / setPlaybackRate / setVolumeCore playback, progress, volume, and playback rate control (rate range 0.25–16×).
Transparent videoErikaVideoAlphaMode.packedAlphaRight / ErikaTextureVideoView(blendMode, opacity)Transparent presentation of side-by-side color/alpha material, with srcOver/overlay blending and opacity (support varies by platform).
Audio tracks and subtitlestracks / selectAudioTrack / selectSubtitleTrack / addExternalSubtitle / removeSubtitleTrack / setSubtitleStyle / registerSubtitleMemoryFontAudio track switching, external SRT/ASS subtitles, font styles, and in-memory font injection.
DanmakuloadDanmakuJson / addDanmakuTrackJson / loadDanmakuFile / addDanmakuTrackFile / danmakuTracks / setDanmakuEnabled / setDanmakuConfig / clearDanmakuDFM+ collision layout, multi-track danmaku, block words, and style configuration. JSON strings follow the unified Danmaku JSON contract.
Image and upscalingsetUpscaler / getUpscalerStatus / screenshot / getPresenterStats / setDebugHudEnabledArtCNN neural 2× upscaling, seamless screenshots, and real-time rendering statistics.
Event streamevents (Stream<ErikaPlayerEvent>)Listen for playback state, buffering, duration changes, and errors.

Since 0.3.1, open(startPosition:) requests the initial position, ErikaEventKind.ended signals natural completion, and setSubtitleDelay and subtitleText() control delay and read the current subtitle. The open return value indicates whether the native runtime accepted the starting position; older runtimes may return false.

Listening for events#

Listen to the player event stream

_player.events.listen((event) {
  switch (event.kind) {
    case ErikaEventKind.stateChanged:
      debugPrint('Playback state: ${event.state}');
    case ErikaEventKind.durationChanged:
      debugPrint('Duration: ${event.duration}');
    case ErikaEventKind.positionChanged:
      debugPrint('Position: ${event.position}');
    case ErikaEventKind.bufferingChanged:
      debugPrint('Buffering: ${event.buffering}');
    case ErikaEventKind.error:
      debugPrint('Playback error: ${event.error ?? event.message}');
    default:
      break;
  }
});

HTTP cache#

httpReadAheadBytes sets how many bytes to read ahead (default 2 MiB). httpBackBufferBytes sets how much already-played data to keep (default 16 MiB). Omit either one or pass 0 to use its default. You can also set the read-ahead default with ERIKA_HTTP_READAHEAD_BYTES.

A backward seek that lands inside the back buffer reuses the data already downloaded. High-bitrate video needs a larger budget: keeping about 10 seconds of an 80 Mbit/s stream takes roughly 100 MB. The cache is limited by bytes, not by a fixed number of seconds of playback.

Dart

await player.open(
  'https://example.com/video.mp4',
  httpReadAheadBytes: 8 * 1024 * 1024,
  httpBackBufferBytes: 128 * 1024 * 1024,
);
await player.play();

GIF export#

ErikaPlayer.exportGif() uses a separate headless pipeline. It needs no video view and does not affect current playback. Pass the start and end times of the clip, the frame rate, and the output size:

Dart

final result = await ErikaPlayer.exportGif(
  ErikaGifExportOptions(
    inputUri: '/path/input.mp4',
    outputPath: '/path/output.gif',
    start: const Duration(seconds: 5),
    end: const Duration(seconds: 10),
    framesPerSecond: 10,
    outputWidth: 640,
    outputHeight: 360,
    quality: ErikaGifExportQuality.high,
  ),
);

In 0.3.4, each Flutter player on Windows, Linux, OpenHarmony, macOS, iOS and tvOS uses a dedicated native thread to serialize media operations, rendering and disposal; frame requests are coalesced. Set ERIKA_FLUTTER_FRAME_TRACE=1 to diagnose thread ownership.

liberika v0.3.8 Section Guide License MPL-2.0