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便可將插件下載到本地。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平臺沒有外部存儲目錄的概念,因此沒法獲取外部存儲目錄路徑,使用時要注意區分。

使用方法

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的使用方法,這樣就能夠知足批量數據的持久化存儲需求了。

說明:

文章轉載自對應的「Flutter編程指南」微信公衆號,更多Flutter相關技術文章打開微信掃描二維碼關注微信公衆號獲取。

相關文章
相關標籤/搜索