前言
本篇将给大家分享Flutter中的file存储功能,Flutter SDK本身已经有File相关的api,所以在Flutter中使用file存储的关键是如何获取手机中存储的目录,然后根据目录路径来创建不同的file。根据Flutter的特性,我们可以通过自定义channel来获取平台端的可存储文件夹路径给flutter端,实现起来非常简单,且这个插件在pub.dartlang.org上已经存在,插件名为path_provider,下面我们就通过引入该插件实现文件存储功能。
file存储使用
引入插件
在pubspec.yaml文件中添加path_provider插件,最新版本为0.4.1,如下:
dependencies: flutter: sdk: flutter #path_provider插件 path_provider: 0.4.1
然后命令行执行 flutter packages get 即可将插件下载到本地。
通过查看插件中的path_provider.dart代码,我们发现它提供了三个方法:
getTemporaryDirectory()
获取临时目录
getApplicationDocumentsDirectory()
获取应用文档目录
getExternalStorageDirectory()
获取外部存储目录
其中getExternalStorageDirectory()方法中代码有平台类型的判断:
Future<Directory> getExternalStorageDirectory() async { if (Platform.isIOS) //如果是iOS平台则抛出不支持的错误 throw new UnsupportedError("Functionality not available on iOS"); final String path = await _channel.invokeMethod('getStorageDirectory'); if (path == null) { return null; } return new Directory(path); }
由此可以看出iOS平台没有外部存储目录的概念,所以无法获取外部存储目录路径,使用时要注意区分。
使用方法
1. 插件引入到项目后,在使用的dart文件中导入path_provider.dart文件import 'package:path_provider/path_provider.dart';2. 获取文件目录,并根据目录创建存储数据的文件对象,将数据写入文件
// 获取应用文档目录并创建文件 Directory documentsDir = await getApplicationDocumentsDirectory(); String documentsPath = documentsDir.path; File file = new File('$documentsPath/notes'); if(!file.existsSync()) { file.createSync(); } writeToFile(context, file, notes); //将数据内容写入指定文件中 void writeToFile(BuildContext context, File file, String notes) async { File file1 = await file.writeAsString(notes); if(file1.existsSync()) { Toast.show(context, '保存成功'); } }iOS模拟器中file的路径为
/Users/.CoreSimulator/Devices/D44E9E54-2FDD-40B2-A953-3592C1D0BFD8/data/Containers/Data/Application/28644C62-1FFA-422E-8ED6-54AA4E9CBE0C/Documents/notesAndroid模拟器中file的路径为
/data/user/0/com.example.demo/app_flutter/notes3. 读取存储到指定文件中的数据
void getNotesFromCache() async { Directory documentsDir = await getApplicationDocumentsDirectory(); String documentsPath = documentsDir.path; File file = new File('$documentsPath/notes'); if(!file.existsSync()) { return; } String notes = await file.readAsString(); //读取到数据后设置数据更新UI setState(() { ... }); }
写在最后
文件存储功能在path_provider插件的基础上实现起来很简单,就介绍到这里,下一篇我们将介绍数据库存储插件sqflite的使用方法,这样就可以满足批量数据的持久化存储需求了。
查看更多关于Flutter持久化存储之文件存储的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did129355