Flutter文件保存插件flutter_saver的使用

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

Flutter文件保存插件flutter_saver的使用

功能

这个Flutter包提供了一个强大且多功能的解决方案,用于在所有平台上保存相机图像和可下载链接。它支持各种格式,允许开发者高效地将图像和文件存储在设备内存中。

特性

  • 您可以在任何平台上使用此代码来保存图像。
  • 本地图片使用示例:
FlutterSaver.saveImageWindowsWeb(fileImage: fileImage);
FlutterSaver.saveImageAndroid(fileImage: fileImage);
FlutterSaver.saveImageIos(fileImage: fileImage);
FlutterSaver.saveImageMacOs(fileImage: fileImage);
  • 示例:
await FlutterSaver.saveImageWindowsWeb(
  fileImage: fileImage,
  fileName: 'example',
  type: 'jpg',
);
  • 网络图片使用示例:
FlutterSaver.saveFileWindowsWeb(link: link);
FlutterSaver.saveFileAndroid(link: link);
FlutterSaver.saveFileIos(link: link);
FlutterSaver.saveFileMac(link: link);
  • 示例:
GestureDetector(
  onTap: () async {
    Future<bool> isSaved = FlutterSaver.saveFileAndroid(
        link: "https://platinumlist.net/guide/wp-content/uploads/2023/03/IMG-worlds-of-adventure.webp");

    if (await isSaved) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Image saved successfully!')),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Failed to save image.')),
      );
    }
  },
  child: Image.network(
    width: 300,
    height: 450,
    "https://platinumlist.net/guide/wp-content/uploads/2023/03/IMG-worlds-of-adventure.webp"),
),
  • 支持的格式:
{
  'image/jpeg': '.jpg',
  'image/png': '.png',
  // 其他格式省略...
}

开始使用

pubspec.yaml中添加依赖:

dependencies:
  flutter_saver: ^0.0.3

或者从GitHub获取:

dependencies:
  flutter_saver:
    git:
      url: https://github.com/SwanFlutter/flutter_saver.git

如何使用

导入库:

import 'package:flutter_saver/flutter_saver.dart';
步骤:
  1. 前往项目路径:

    android/app/src/main/AndroidManifest.xml
    
  2. AndroidManifest.xml文件中添加以下权限:

    • 对于Android版本低于33:
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <!-- Android 10及以上访问外部存储 -->
    <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
    
    <!-- Android 12及以上 -->
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage"/>
    
    • 对于Android版本33及以上(Android 13):
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
    
    • 相机和互联网访问权限:
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    
    • 添加这行代码到应用的AndroidManifest.xml
    android:requestLegacyExternalStorage="true"
    
    <application
        android:label="avaterbetter"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:requestLegacyExternalStorage="true">
    
    • 添加查询:
    <queries>
        <intent>
            <action android:name="android.intent.action.GET_CONTENT" />
        </intent>
    </queries>
    
iOS设置:
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select images for editing.</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera to take photos for editing.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photos to save images.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>We need access to your documents folder to save files.</string>
macOS安装:

由于macOS实现使用了file_selector,您需要添加一个文件系统访问权限:

<key>com.apple.security.files.user-selected.read-only</key>
<true/>

完整示例Demo

// ignore_for_file: use_build_context_synchronously

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("Unsplash Images"),
      ),
      body: SizedBox(
        width: size.width,
        height: size.height,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () async {
                Future<bool> isSaved = FlutterSaver.saveFileAndroid(
                    link: "https://platinumlist.net/guide/wp-content/uploads/2023/03/IMG-worlds-of-adventure.webp");

                if (await isSaved) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Image saved successfully!')),
                  );
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Failed to save image.')),
                  );
                }
              },
              child: Image.network(
                width: 300,
                height: 450,
                "https://platinumlist.net/guide/wp-content/uploads/2023/03/IMG-worlds-of-adventure.webp"),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_saver插件来保存文件的示例代码。flutter_saver是一个用于将文件保存到设备存储的Flutter插件。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_saver: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

2. 导入插件

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

import 'package:flutter_saver/flutter_saver.dart';

3. 请求权限

在Android上,你需要请求存储权限。可以在AndroidManifest.xml中添加必要的权限:

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

然后,在运行时请求权限(可以使用permission_handler插件或其他类似插件)。以下是一个使用permission_handler的示例:

import 'package:permission_handler/permission_handler.dart';

Future<bool> requestStoragePermission() async {
  var status = await Permission.storage.status;
  if (!status.isGranted) {
    var result = await Permission.storage.request();
    if (result.isGranted) {
      return true;
    } else if (result.isDenied || result.isPermanentlyDenied) {
      return false;
    }
  } else {
    return true;
  }
}

4. 保存文件

以下是使用flutter_saver保存文件的示例代码:

import 'dart:typed_data/uint8list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_saver/flutter_saver.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Saver Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              bool hasPermission = await requestStoragePermission();
              if (hasPermission) {
                Uint8List data = Uint8List.fromList('Hello, Flutter Saver!'.codeUnits);
                String fileName = 'example.txt';
                String mimeType = 'text/plain';

                bool isSaved = await FlutterSaver.saveFile(
                  fileData: data,
                  fileName: fileName,
                  mimeType: mimeType,
                );

                if (isSaved) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('File saved successfully!')),
                  );
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Failed to save file.')),
                  );
                }
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Storage permission denied.')),
                );
              }
            },
            child: Text('Save File'),
          ),
        ),
      ),
    );
  }
}

5. 注意事项

  • 确保你已经正确配置了AndroidManifest.xml和其他必要的配置文件。
  • 在实际项目中,你可能需要处理更多的错误情况和边界条件。
  • flutter_saver插件可能不适用于所有平台,请查阅其官方文档以获取更多信息。

通过上述步骤,你应该能够在Flutter项目中成功使用flutter_saver插件来保存文件。

回到顶部