media_source library

A comprehensive media source management library for Flutter and Dart.

This library provides a unified API for handling media files from different sources including local files, in-memory data, and network URLs. It supports various media types such as video, audio, images, and documents.

Features

  • Multiple Source Types: Work with files, memory buffers, or network URLs
  • Type-Safe Media Classification: Strongly-typed media types (Video, Audio, Image, Document)
  • Cross-Platform Support: Works on mobile, web, and desktop platforms
  • Size-Aware: Built-in file size handling with FileSize support
  • Flexible Conversions: Convert between different source types (e.g., file to memory)
  • File Operations: Move, copy, save, and delete operations for file-based media

Extensibility

You can extend this library in three ways:

  1. Define your own media type by extending FileTypeImpl (see src/media_type.dart). This is useful when your domain has custom classifications (e.g., StickerType, SubtitleType).

  2. Create new media sources by extending MediaSource<M> or implementing the conversion mixins (ToFileConvertableMedia, ToMemoryConvertableMedia) to fit your storage/transport needs.

  3. Create custom media factories to centralize media instantiation logic and apply business rules, optimizations, or testing strategies.

Example – custom media type and memory source:

class StickerType extends FileTypeImpl {
  StickerType() : super.copy(FileType.other);
  @override
  List<Object?> get props => const [];
}

class StickerMemoryMedia extends MemoryMediaSource<StickerType> {
  StickerMemoryMedia(Uint8List bytes, {required String name})
      : super._(bytes, name: name, metadata: StickerType());

  @override
  Future<FileMediaSource<StickerType>> saveTo(String path) async {
    final file = XFile.fromData(bytes, name: name, path: path);
    await PlatformUtils.instance.createDirectoryIfNotExists(path);
    await file.saveTo(path);
    // Provide your own FileMediaSource implementation for StickerType
    throw UnimplementedError('Provide a FileMediaSource<StickerType>');
  }
}

Example – custom media factory:

class MediaFactory {
  dynamic createMedia({
    required MediaSourceType source,
    String? path,
    Uint8List? bytes,
    String? url,
  }) async {
    switch (source) {
      case MediaSourceType.file:
        if (path != null) {
          final fileType = await FileType.fromPath(path);
          // Create appropriate media based on type
          if (fileType is VideoType) {
            return VideoFileMedia.fromPath(path);
          }
          // Handle other types...
        }
        break;
      // Handle memory and network cases...
    }
  }
}

Usage

// Working with file media
final video = await VideoFileMedia.fromPath('path/to/video.mp4');
await video.saveTo('backup/video.mp4');

// Working with memory media
final image = ImageMemoryMedia(imageBytes, name: 'photo.jpg');
final savedFile = await image.saveToFolder('images');

// Working with network media
final audio = AudioNetworkMedia.url(
  'https://example.com/song.mp3',
  name: 'song.mp3',
  size: 5.mb,
);

// Type-safe pattern matching with fold
final result = media.fold(
  file: (f) => 'File: ${f.file.path}',
  memory: (m) => 'Memory: ${m.size}',
  network: (n) => 'URL: ${n.uri}',
  asset: (a) => 'Asset: ${a.assetPath}',
  orElse: () => 'Unknown',
);

Classes

AssetMediaSource<M extends FileType>
Abstract base class for Flutter asset-based media sources.
AudioAssetMedia
Represents audio assets from the Flutter asset bundle.
AudioFileMedia
Represents audio files stored on the file system.
AudioMemoryMedia
Represents audio data stored in memory.
AudioNetworkMedia
Represents audio URLs (streaming media).
AudioType
Media type for audio files.
DocumentAssetMedia
Represents document assets from the Flutter asset bundle.
DocumentFileMedia
Represents document files stored on the file system.
DocumentMemoryMedia
Represents document data stored in memory.
DocumentNetworkMedia
Represents document URLs.
DocumentType
Media type for document files (primarily PDF).
DurationMedia
Interface for media types that have duration information.
FileMediaSource<M extends FileType>
Abstract base class for file-based media sources.
FileSize
A utility class for handling file size conversions and formatting.
FileTypeImpl
Base class for defining custom media type variants.
ImageAssetMedia
Represents image assets from the Flutter asset bundle.
ImageFileMedia
Represents image files stored on the file system.
ImageMemoryMedia
Represents image data stored in memory.
ImageNetworkMedia
Represents image URLs.
ImageType
Media type for image files.
MediaSource<M extends FileType>
Abstract base class for all media sources.
MemoryMediaSource<M extends FileType>
Abstract base class for in-memory media sources.
NetworkMediaSource<M extends FileType>
Abstract base class for network-based media sources.
OtherType
Media type for other/unclassified file types.
OtherTypeAssetMedia
Represents assets of unclassified or unknown types.
OtherTypeFileMedia
Represents files of unclassified or unknown types.
OtherTypeMemoryMedia
Represents unclassified or unknown data stored in memory.
PlatformUtils
Platform-specific utilities used throughout the package.
PlatformUtilsFacade
Facade interface implemented by platform-specific utilities.
ThumbnailMediaSource<M extends FileType, T extends FileType>
A MediaSource that wraps an original source and an optional thumbnail source.
ToFileConvertableMedia<M extends FileType>
Mixin for media sources that can be saved as files.
ToMemoryConvertableMedia<M extends FileType>
Mixin for media sources that can be converted to MemoryMediaSource.
UnSupportedNetworkMedia
Represents URLs for media types that don't fit standard categories.
UrlMedia
Represents a generic URL, separate from media classification.
UrlType
Media type for URL references.
VideoAssetMedia
Represents video assets from the Flutter asset bundle.
VideoFileMedia
Represents video files stored on the file system.
VideoMemoryMedia
Represents video data stored in memory.
VideoNetworkMedia
Represents video URLs (streaming media).
VideoType
Media type for video files.

Extensions

MediaTypeExtension on FileTypeImpl
Extension on FileTypeImpl providing pattern matching functionality.
NumericExtensions on num
Convenient extension methods on num for creating FileSize instances.