Flutter数据保存插件jsaver的使用

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

Flutter数据保存插件jsaver的使用

jsaver

JSaver 是一个强大的文件保存插件,支持在 Android、Web、Linux 和 Windows 上将文件保存到用户选择的目录。

特性

  • 设置默认保存目录
  • 获取默认保存目录
  • 获取应用目录
  • 获取缓存目录并清理缓存目录
  • 从文件列表、路径、FilesModel 保存文件
  • 从单个文件保存
  • 从 Uint8List 保存
  • 从路径保存

使用方法

Android

最低 SDK 版本:

minSdkVersion 21

Web

Web 平台仅支持以下方法:

final _jSaverPlugin = JSaver();

Future<String> saveFromData(Uint8List data, String fileName) async {
  // 注意:文件名必须包含扩展名
  final value = await _jSaverPlugin.saveFromData(data: data, name: fileName);
  return value;
}

简单用法

final _jSaverPlugin = JSaver.instance;

设置和获取默认目录

Future<FilesModel> setDefaultDirectory() async {
  final value = await _jSaverPlugin.setDefaultSavingDirectory();
  return value;
}

Future<FilesModel> getDefaultDirectory() async {
  final value = await _jSaverPlugin.getDefaultSavingDirectory();
  return value;
}

授予目录访问权限和获取已访问目录

Future<FilesModel> grantAccessToDirectory() async {
  final value = await _jSaverPlugin.grantAccessToDirectory();
  return value;
}

Future<List<FilesModel>> getAccessedDirectories() async {
  final value = await _jSaverPlugin.getAccessedDirectories();
  return value;
}

获取和清理缓存目录

Future<String> getApplicationCacheDirectory() async {
  final value = await _jSaverPlugin.getCacheDirectory();
  return value;
}

Future<String> cleanApplicationCacheDirectory() async {
  final value = await _jSaverPlugin.cleanApplicationCache();
  return value;
}

保存所有方法

FilesModel fileModel = FilesModel("File Name With Extension", "Full File Path", [Uint8List data]);
// 如果在 FilesModel 中添加了文件路径,则不需要添加文件名和数据

FilesModel fileModel = FilesModel("", "", [Uint8List data]);
// 如果在 FilesModel 中添加了文件数据,则必须添加带有扩展名的文件名,并且路径留空

Future<List<FilesModel>> save() async {
  final file1 = File("/storage/emulated/0/SourceFolder/file.jpg");
  final fileModel1 = FilesModel("file.jpg", "", file1.readAsBytesSync());
  final fileModel2 = FilesModel("", "/storage/emulated/0/SourceFolder/file.jpg");
  final value = await _jSaverPlugin.save(
    fromPath: file1.path,
    fromFile: file1,
    fromData: fileModel1,
    fromFiles: [file1],
    fromPaths: [file1.path],
    fromDataList: [fileModel1, fileModel2],
    toDirectory: "/storage/emulated/0/TargetFolder" || "D:/Folder/TargetFolder",
    androidPathOptions: AndroidPathOptions(
      cleanCache: true,
      toDefaultDirectory: false,
    ),
  );
  return value;
}

示例代码

以下是一个完整的示例代码,展示了如何使用 jsaver 插件进行文件操作:

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:jsaver/jSaver.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _savedFile = 'Unknown';
  final _jSaverPlugin = JSaver.instance;

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('$_savedFile\n'),
        ),
        floatingActionButton: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FloatingActionButton(
              heroTag: '1',
              onPressed: () async {
                await savedWeb();
              },
              child: const Icon(Icons.web),
            ),
            FloatingActionButton(
              heroTag: '2',
              onPressed: () async {
                await Permission.storage.request();
                final val = await _jSaverPlugin.grantAccessToDirectory();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val.toString();
                });
              },
              child: const Icon(Icons.lock_open),
            ),
            FloatingActionButton(
              heroTag: '3',
              onPressed: () async {
                await Permission.storage.request();
                final val = await _jSaverPlugin.getAccessedDirectories();
                for (var i in val) {
                  debugPrint(i.toString());
                }
                setState(() {
                  _savedFile = val.first.toString();
                });
              },
              child: const Icon(Icons.storage),
            ),
            FloatingActionButton(
              heroTag: '4',
              onPressed: () async {
                final val = await _jSaverPlugin.setDefaultSavingDirectory();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val.toString();
                });
              },
              child: const Icon(Icons.maps_home_work),
            ),
            FloatingActionButton(
              heroTag: '5',
              onPressed: () async {
                final val = await _jSaverPlugin.getDefaultSavingDirectory();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val.toString();
                });
              },
              child: const Icon(Icons.home),
            ),
            FloatingActionButton(
              heroTag: '6',
              onPressed: () async {
                final val = await saveAll();
                if (val.isNotEmpty) {
                  for (var i in val) {
                    debugPrint(i.toString());
                  }
                  setState(() {
                    _savedFile = val.first.toString();
                  });
                }
              },
              child: const Icon(Icons.save),
            ),
            FloatingActionButton(
              heroTag: '7',
              onPressed: () async {
                final val = await _jSaverPlugin.getCacheDirectory();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val.toString();
                });
              },
              child: const Icon(Icons.cached_sharp),
            ),
            FloatingActionButton(
              heroTag: '8',
              onPressed: () async {
                final val = await _jSaverPlugin.cleanAppCacheDirs();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val.toString();
                });
              },
              child: const Icon(Icons.cleaning_services),
            ),
            FloatingActionButton(
              heroTag: '9',
              onPressed: () async {
                final val = await _jSaverPlugin.getApplicationDirectory();
                debugPrint(val.toString());
                setState(() {
                  _savedFile = val;
                });
              },
              child: const Icon(Icons.storage),
            ),
          ],
        ),
      ),
    );
  }

  savedWeb() async {
    final val = await FilePicker.platform.pickFiles(allowMultiple: false);
    if (val != null) {
      if (val.files.isNotEmpty) {
        final file = val.files.first;
        if (file.bytes != null) {
          debugPrint(file.extension.toString());
          debugPrint(file.name.toString());
          debugPrint(file.bytes.toString());
          final v = await _jSaverPlugin.saveFromData(
              data: file.bytes!, name: file.name);
          setState(() {
            _savedFile = v;
          });
          debugPrint(v.toString());
        }
      }
    }
  }

  Future<List<FilesModel>> saveAll() async {
    if (!Platform.isLinux) {
      await Permission.storage.request();
    }
    final val = await FilePicker.platform.pickFiles(allowMultiple: true);
    if (val != null) {
      if (val.paths.isNotEmpty || val.files.isNotEmpty) {
        List<String> paths = [];
        List<File> files = [];
        List<FilesModel> filesData = [];
        for (var i in val.paths) {
          if (i != null) {
            paths.add(i);
            // filesData.add(FilesModel(fPath: i));
          }
        }
        for (var i in val.files) {
          if (i.path != null) {
            final vF = File(i.path!);
            files.add(vF);
            filesData.add(FilesModel(
                vF.path.substring(vF.path.lastIndexOf(Platform.pathSeparator) + 1),
                "",
                vF.readAsBytesSync()));
          }
        }
        final v = await _jSaverPlugin.save(
          fromPath: paths.first,
          fromFile: files.first,
          fromData: filesData.first,
          fromFiles: files,
          fromPaths: paths,
          fromDataList: filesData,
          // toDirectory: "D:/NewFolder/Folder",
          // toDirectory: "/storage/emulated/0/TargetFolder",
          androidPathOptions: AndroidPathOptions(
            cleanCache: true,
            toDefaultDirectory: false,
          ),
        );
        return v;
      } else {
        return [];
      }
    } else {
      return [];
    }
  }
}

额外信息

Just Codes Developers 提供。


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

1 回复

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


当然,关于Flutter数据保存插件jsaver的使用,下面是一个具体的代码示例,展示了如何在Flutter项目中集成并使用jsaver来保存和读取数据。

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

dependencies:
  flutter:
    sdk: flutter
  jsaver: ^最新版本号  # 请替换为实际可用的最新版本号

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

接下来,我们编写一个示例应用,展示如何使用jsaver来保存和读取简单的键值对数据。

示例代码

main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter JSaver Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _jsaver = JSaver();
  final _key = 'example_key';
  String _savedValue = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter JSaver Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              decoration: InputDecoration(labelText: 'Enter a value'),
              onChanged: (value) {
                _savedValue = value;
              },
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () async {
                await _jsaver.setString(_key, _savedValue);
                setState(() {
                  // 刷新界面以反映新值(虽然在这个例子中立即读取值,但通常不需要)
                  _readValue();
                });
              },
              child: Text('Save Value'),
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () async {
                String? value = await _jsaver.getString(_key);
                setState(() {
                  _savedValue = value ?? '';
                });
              },
              child: Text('Read Value'),
            ),
            SizedBox(height: 16.0),
            Text('Saved Value: $_savedValue'),
          ],
        ),
      ),
    );
  }

  Future<void> _readValue() async {
    String? value = await _jsaver.getString(_key);
    setState(() {
      _savedValue = value ?? '';
    });
  }
}

说明

  1. 依赖导入:首先,我们在pubspec.yaml文件中添加了jsaver依赖。
  2. UI布局:在MyHomePage中,我们创建了一个简单的UI,包含一个TextField用于输入值,两个ElevatedButton分别用于保存和读取值,以及一个Text用于显示保存的值。
  3. 保存数据:点击“Save Value”按钮时,调用_jsaver.setString(_key, _savedValue)方法将数据保存到本地存储。
  4. 读取数据:点击“Read Value”按钮时,调用_jsaver.getString(_key)方法从本地存储中读取数据,并更新UI显示。

这个示例展示了如何使用jsaver插件在Flutter应用中保存和读取简单的字符串数据。你可以根据需要扩展这个示例,以保存和读取更复杂的数据类型。

回到顶部