Different platforms have different file systems, such as file paths. Therefore, obtaining file paths in Flutter requires the native endpoint to pass the file path through a Channel, which is inconvenient. We recommend using the official plugin path_provider to implement this function.

File system directory

Different platforms have different file systems, such as file paths. You are advised to use path_provider, a plug-in officially maintained by Google

Add the dependent

Add dependencies to the project’s pubspec.yaml file:

Dependencies: path_provider: ^ mid-atlantic movedCopy the code

Execute command:

flutter pub get
Copy the code

The file path

The path_provider provides eight methods to obtain different file paths:

  • GetTemporaryDirectory: Path to an unbacked temporary directory on the device, suitable for storing a cache of downloaded files, which can be removed at any time. On iOS, the directory is obtained from NSCachesDirectory. On Android, the directory is getCacheDir.

  • GetApplicationSupportDirectory: in which the application can place application support file directory path.

Use this option for files that you do not want exposed to the user. Your application should not use this directory to store user data files. IOS is equivalent to NSApplicationSupportDirectory API access, and if the directory does not exist, is automatically created. The Android equivalent is the getFilesDir directory.

  • GetLibraryDirectory: Directory where the application can store persistent files, backup files, and directory paths for files that are not visible to the user, such as sqlite.db. On Android, this function raises an UnsupportedError exception, and no equivalent path exists.

  • GetApplicationDocumentsDirectory: applications may be placed data directory path or the application can’t recreate the data directory path. On iOS, this corresponds to the NSDocumentDirectory API. If the data is not user generated, consider using getApplicationSupportDirectory. On Android, this corresponds to the getDataDirectory API. If you want to let users see the data, please consider to switch to external.getexternalstoragedirectory.

  • External.getexternalstoragedirectory: applications can access the top storage directory path. Since this feature is only available on Android, you should determine the current operating system before issuing this function call. On iOS, this feature raises an UnsupportedError exception because it cannot be accessed outside the application sandbox. On Android, this corresponds to getExternalFilesDir (null).

  • GetExternalCacheDirectories: storage is specific to the application of external cache data directory path. These paths are usually on external storage (such as a separate partition or SD card), and this feature is only accessible on Android.

  • GetExternalStorageDirectories: can store application specific data directory path. These paths are typically located on external storage, such as a separate partition or SD card. Since this feature is only available on Android.

  • GetDownloadsDirectory: The path to the directory where the downloaded files are stored, which is usually only relevant to the desktop operating system. On Android and iOS, this function raises an UnsupportedError exception.

IOS File Storage

Data stored locally in iOS is kept in a sandbox. To ensure system security, each iOS application creates its own sandbox file (storage space) during installation. IOS sandbox directory:

  • Documents: iTunes will back up this directory. Typically used to store data that needs to be persisted. Corresponding getApplicationDocumentsDirectory method
  • Library/Caches: This directory is not backed up by iTunes. It may be cleared when the application is not running. Generally, the storage volume is large and non-important data does not need to be backed up. Corresponds to the getTemporaryDirectory method
  • Library/Preference: iTunes also backs up this directory and can be used to store preferences.
  • TMP: iTunes does not back up this directory. It is used to store temporary data. Data in this directory will be cleared when the app exits.

Flutter obtains the cache file path

void getTempDir() async {
  Directory tempDir = await getTemporaryDirectory();
  print(tempDir.path);
}
Copy the code

flutter: /Users/zhouCandy/Library/Developer/CoreSimulator/Devices/9853F2BA-DC9C-4E8C-9C4D-B2C00BFA83ED/data/Containers/Data/Appli cation/CF9BDC93-0F20-4D75-88CC-4C2AC205B532/Library/Caches

Path for iOS to obtain cache files

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cachesDir = [paths objectAtIndex:0];
Copy the code

/Users/zhouCandy/Library/Developer/CoreSimulator/Devices/9853F2BA-DC9C-4E8C-9C4D-B2C00BFA83ED/data/Containers/Data/Appli cation/7F78738D-2F77-4654-83F2-8DB0B28ACA45/Library/Caches

It can be seen that the corresponding path of the primary and Flutter acquisition is the same

File to read and write

Path_provider use

Here, input text, save the content of the text, and then read out the saved content and the path of the file. Here, the iOS simulator is used to test

import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'dart:io'; class SaveDataPage extends StatefulWidget { const SaveDataPage({Key? key}) : super(key: key); @override _SaveDataPageState createState() => _SaveDataPageState(); } class _SaveDataPageState extends State<SaveDataPage> { final _textFieldController = TextEditingController(); var _saveString = ''; SaveString () async {final file = await getFile('file.text'); / / write a string file. WriteAsString (_textFieldController. Value. The text. The toString ()); Future getString() async {final file = await getFile('file.text'); var filePath = file.path; print('${filePath}'); SetState (() {file.readasString (). Then ((String value) {_saveString = value +'\n File storage path: '+filePath; }); }); } // Initialize the File path Future<File> getFile(String fileName) async {// Get the application File directory similar to NSDocumentDirectory on iOS and AppData directory on Android final  fileDirectory = await getApplicationDocumentsDirectory(); Final filePath = filedirectory.path; Dart: IO ') return file (filePath + "/"+fileName); } @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (title: const Text(' data store '),), body: The Column (mainAxisAlignment: mainAxisAlignment center, children: < widgets > [const Text (" file storage, "textAlign: TextAlign.center), TextField( controller: _textFieldController, ), MaterialButton( onPressed: saveString, child: Const Text(" store "), color: color.cyan,), MaterialButton(onPressed: getString, Child: const Text(" retrieve "), color: Color.deeporange,), Text(' stored value is $_saveString'),],),); }}Copy the code

The actual effect

This is how to get the file directory, and how to read and write files.