Flutter媒体文件保存插件flutter_media_gallery_saver的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter媒体文件保存插件flutter_media_gallery_saver的使用

在本教程中,我们将介绍如何使用 flutter_media_gallery_saver 插件将不同类型的媒体文件保存到设备的相册或存储中。该插件支持保存图片、GIF 和视频文件。

使用步骤

1. 添加依赖

首先,在项目的 pubspec.yaml 文件中添加 flutter_media_gallery_saver 和其他必要的依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_media_gallery_saver: ^1.0.0
  dio: ^5.0.0
  fluttertoast: ^8.0.8
  permission_handler: ^10.0.0
  path_provider: ^2.0.9

然后运行以下命令以安装依赖:

flutter pub get

2. 请求权限

在 Android 和 iOS 上保存文件需要访问存储权限。我们需要请求这些权限。

import 'package:permission_handler/permission_handler.dart';

void _requestPermission() async {
  Map<Permission, PermissionStatus> statuses = await [
    Permission.storage,
  ].request();

  final info = statuses[Permission.storage].toString();
  print(info);
  _toastInfo(info);
}

3. 使用插件保存文件

保存网络图片

_getHttp() async {
  // 下载图片数据
  var response = await Dio().get(
      "https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
      options: Options(responseType: ResponseType.bytes));

  // 保存图片到相册
  final result = await FlutterMediaGallerySaver.saveImage(
      Uint8List.fromList(response.data),
      quality: 60,
      name: "hello");

  print(result);
  _toastInfo("$result");
}

保存GIF文件

_saveGif() async {
  // 获取临时目录
  var appDocDir = await getTemporaryDirectory();
  String savePath = appDocDir.path + "/temp.gif";

  // 下载GIF文件
  String fileUrl =
      "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
  await Dio().download(fileUrl, savePath);

  // 保存到相册
  final result = await FlutterMediaGallerySaver.saveImageWithUrl(savePath);
  print(result);
  _toastInfo("$result");
}

保存视频文件

_saveVideo() async {
  var appDocDir = await getTemporaryDirectory();
  String savePath = appDocDir.path + "/temp.mp4";

  // 检查文件是否存在,如果不存在则下载
  if (File(savePath).existsSync()) {
    final result = await FlutterMediaGallerySaver.saveVideo(savePath);
    print(result);
    _toastInfo("$result");
  } else {
    String fileUrl =
        "https://v-cdn.zjol.com.cn/276982.mp4";
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      print((count / total * 100).toStringAsFixed(0) + "%");
    });

    // 保存到相册
    final result = await FlutterMediaGallerySaver.saveVideo(savePath);
    print(result);
    _toastInfo("$result");
  }
}

保存大视频文件

_saveLargerVideo() async {
  var appDocDir = await getTemporaryDirectory();
  String savePath = appDocDir.path + "/larger_temp.mp4";

  // 检查文件是否存在,如果不存在则下载
  if (File(savePath).existsSync()) {
    print("开始保存: ${DateTime.now().millisecondsSinceEpoch}");
    final result = await FlutterMediaGallerySaver.saveVideo(savePath);
    print("保存结束: ${DateTime.now().millisecondsSinceEpoch}");
    print(result);
    _toastInfo("$result");
  } else {
    String fileUrl =
        "http://v.hbang.com.cn/d/11fc628d-8d4a-4153-8c0f-0ee6072ca40e.mp4";
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      setState(() {
        progress = (count / total * 100).toStringAsFixed(0) + "%";
      });
      print((count / total * 100).toStringAsFixed(0) + "%");
    });

    // 保存到相册
    final result = await FlutterMediaGallerySaver.saveVideo(savePath);
    print(result);
    _toastInfo("$result");
  }
}

4. 完整示例代码

以下是完整的示例代码,展示了如何实现上述功能:

import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';
import 'package:flutter_media_gallery_saver/flutter_media_gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '保存到相册',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _globalKey = GlobalKey();
  int index = 0;
  late Timer timer;

  var progress = '0';

  [@override](/user/override)
  void initState() {
    super.initState();
    _requestPermission();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        index++;
      });
    });
  }

  [@override](/user/override)
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
    _toastInfo(info);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Save to gallery"),
      ),
      body: Center(
        child: Column(
          children: [
            RepaintBoundary(
              key: _globalKey,
              child: Container(
                width: 200,
                height: 200,
                color: Colors.red,
                child: Center(
                  child: Text('$index'),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _getHttp,
                child: Text("保存网络图片"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveGif,
                child: Text("保存GIF"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveVideo,
                child: Text("保存视频"),
              ),
              width: 200,
            ),
            Container(
              padding: EdgeInsets.only(top: 15),
              child: TextButton(
                onPressed: _saveLargerVideo,
                child: Text("保存大视频--$progress"),
              ),
              width: 200,
            ),
          ],
        ),
      ),
    );
  }

  _getHttp() async {
    var response = await Dio().get(
        "https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
        options: Options(responseType: ResponseType.bytes));
    final result = await FlutterMediaGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        quality: 60,
        name: "hello");
    print(result);
    _toastInfo("$result");
  }

  _saveGif() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.gif";
    String fileUrl =
        "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
    await Dio().download(fileUrl, savePath);
    final result = await FlutterMediaGallerySaver.saveImageWithUrl(savePath);
    print(result);
    _toastInfo("$result");
  }

  _saveVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    if (File(savePath).existsSync()) {
      final result = await FlutterMediaGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    } else {
      String fileUrl =
          "https://v-cdn.zjol.com.cn/276982.mp4";
      await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
        print((count / total * 100).toStringAsFixed(0) + "%");
      });
      final result = await FlutterMediaGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    }
  }

  _saveLargerVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/larger_temp.mp4";
    if (File(savePath).existsSync()) {
      print("开始保存: ${DateTime.now().millisecondsSinceEpoch}");
      final result = await FlutterMediaGallerySaver.saveVideo(savePath);
      print("保存结束: ${DateTime.now().millisecondsSinceEpoch}");
      print(result);
      _toastInfo("$result");
    } else {
      String fileUrl =
          "http://v.hbang.com.cn/d/11fc628d-8d4a-4153-8c0f-0ee6072ca40e.mp4";
      await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
        setState(() {
          progress = (count / total * 100).toStringAsFixed(0) + "%";
        });
        print((count / total * 100).toStringAsFixed(0) + "%");
      });
      final result = await FlutterMediaGallerySaver.saveVideo(savePath);
      print(result);
      _toastInfo("$result");
    }
  }

  _toastInfo(String info) {
    Fluttertoast.showToast(msg: info, toastLength: Toast.LENGTH_LONG);
  }
}

更多关于Flutter媒体文件保存插件flutter_media_gallery_saver的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter媒体文件保存插件flutter_media_gallery_saver的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_media_gallery_saver 是一个用于在 Flutter 应用中保存媒体文件(如照片、视频等)到设备相册的插件。它的主要功能是将文件保存到设备的媒体库中,以便用户可以在系统的相册应用中查看这些文件。

安装

首先,你需要在 pubspec.yaml 文件中添加 flutter_media_gallery_saver 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_media_gallery_saver: ^latest_version

然后运行 flutter pub get 来安装插件。

使用

1. 导入插件

在你的 Dart 文件中导入 flutter_media_gallery_saver 插件:

import 'package:flutter_media_gallery_saver/flutter_media_gallery_saver.dart';

2. 保存图片到相册

你可以使用 saveImageToGallery 方法将图片保存到相册:

Future<void> saveImage() async {
  String filePath = '/path/to/your/image.jpg'; // 图片文件路径
  try {
    final result = await FlutterMediaGallerySaver.saveImageToGallery(filePath);
    print('Image saved to gallery: $result');
  } catch (e) {
    print('Failed to save image: $e');
  }
}

3. 保存视频到相册

你可以使用 saveVideoToGallery 方法将视频保存到相册:

Future<void> saveVideo() async {
  String filePath = '/path/to/your/video.mp4'; // 视频文件路径
  try {
    final result = await FlutterMediaGallerySaver.saveVideoToGallery(filePath);
    print('Video saved to gallery: $result');
  } catch (e) {
    print('Failed to save video: $e');
  }
}

4. 保存文件到相册

你还可以使用 saveFileToGallery 方法保存其他类型的文件到相册:

Future<void> saveFile() async {
  String filePath = '/path/to/your/file.pdf'; // 文件路径
  try {
    final result = await FlutterMediaGallerySaver.saveFileToGallery(filePath);
    print('File saved to gallery: $result');
  } catch (e) {
    print('Failed to save file: $e');
  }
}

权限

在 Android 上,保存文件到相册需要以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

在 iOS 上,你需要在 Info.plist 文件中添加以下权限:

<key>NSPhotoLibraryAddUsageDescription</key>
<string>We need to save photos to your gallery.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need to save photos to your gallery.</string>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!