本篇将给你们分享Flutter中的file存储功能,Flutter SDK自己已经有File相关的api,因此在Flutter中使用file存储的关键是如何获取手机中存储的目录,而后根据目录路径来建立不一样的file。根据Flutter的特性,咱们能够经过自定义channel来获取平台端的可存储文件夹路径给flutter端,实现起来很是简单,且这个插件在pub.dartlang.org上已经存在,插件名为path_provider,下面咱们就经过引入该插件实现文件存储功能。数据库
在pubspec.yaml文件中添加path_provider插件,最新版本为0.4.1,以下:编程
dependencies:
flutter:
sdk: flutter
#path_provider插件
path_provider: 0.4.1
复制代码
而后命令行执行flutter packages get
便可将插件下载到本地。api
经过查看插件中的path_provider.dart代码,咱们发现它提供了三个方法:bash
getTemporaryDirectory()微信
获取临时目录app
getApplicationDocumentsDirectory()async
获取应用文档目录ide
getExternalStorageDirectory()ui
获取外部存储目录spa
其中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平台没有外部存储目录的概念,因此没法获取外部存储目录路径,使用时要注意区分。
import 'package:path_provider/path_provider.dart';
复制代码
// 获取应用文档目录并建立文件
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, '保存成功');
}
}
复制代码
/Users/.../CoreSimulator/Devices/D44E9E54-2FDD-40B2-A953-3592C1D0BFD8/data/Containers/Data/Application/28644C62-1FFA-422E-8ED6-54AA4E9CBE0C/Documents/notes
复制代码
/data/user/0/com.example.demo/app_flutter/notes
复制代码
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编程指南”微信公众号,更多Flutter相关技术文章打开微信扫描二维码关注微信公众号获取。