Line data Source code
1 : import 'dart:async';
2 : import 'package:cross_file/cross_file.dart';
3 : import 'package:file_type_plus/file_type_plus.dart';
4 : import 'package:flutter/foundation.dart';
5 : import 'package:media_source/src/utils/platform_utils.dart';
6 : import 'package:file_sized/file_sized.dart';
7 :
8 : /// Convenience extensions for [XFile] used by this package.
9 : ///
10 : /// Provides platform-agnostic helpers such as deletion via the package's
11 : /// [PlatformUtils] facade, size extraction as a [FileSize], and media type
12 : /// detection.
13 : extension FileExtensions on XFile {
14 : /// Deletes the underlying file/resource using the platform facade.
15 : ///
16 : /// On native platforms this will delete the file from disk. On web it may
17 : /// revoke blob URLs if applicable. Returns `true` when deletion succeeded.
18 0 : Future<bool> delete() async {
19 0 : if (await exists()) return PlatformUtils.instance.deleteFile(this);
20 : return false;
21 : }
22 :
23 : /// Returns the file size wrapped in a [FileSize].
24 : ///
25 : /// Uses the cross-file `length()` and converts to a [FileSize] for
26 : /// convenient human-readable formatting elsewhere in the package.
27 5 : Future<FileSize> size() => length().then((v) => v.b);
28 :
29 : /// Returns `true` when the underlying file/resource exists on the
30 : /// platform (disk, blob URL, etc.).
31 3 : Future<bool> exists() => PlatformUtils.instance.fileExists(this);
32 :
33 : /// Attempts to detect the media type of the file.
34 : ///
35 : /// On web, detection is done from the bytes; on native platforms it's done
36 : /// from the file path and/or mime type.
37 0 : Future<FileType> getMediaType([String? media]) async =>
38 0 : kIsWeb ? FileType.fromBytes(await readAsBytes(), mimeType) : FileType.fromPath(path, mimeType);
39 : }
|