flutter持久化_Flutter持久化存储之文件存储

前言

本篇将给大家分享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 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/notes

Android模拟器中file的路径为

/data/user/0/com.example.demo/app_flutter/notes

3. 读取存储到指定文件中的数据

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的使用方法,这样就可以满足批量数据的持久化存储需求了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值