Preface
In our actual application development process, we often do some local persistent data configuration, which can be obtained when the application starts to process the corresponding business logic. Or we need to download files, download pictures, etc. through the IO
stream.
When we manipulate files we need to combine dart:io
library path_provider
, because of the different file paths under each system, if they are to achieve a lot of trouble, so path_provider
this production.
Source code and video tutorial address
github source code address video tutorial address
Introduction to path_provider
path_provider
is a Flutter
plug-in. Its main function is to provide a platform-independent and consistent way to access the file system of the device, such as application temporary directories and document directories. And path_provider
supports Android , iOS , Linux , MacOS , Windows .
path_provider App directory
There are eight types of app storage directories. Let’s take a look at their differences:
Temporary directory
The temporary directory is a cache folder that the system can empty at any time
- The corresponding implementation for iOS is
NSCachesDirectory
- The corresponding implementation for Android is
getCacheDir()
)
Document directory
The document directory is used to store files that can only be accessed by the application. The system will not clear the directory and will only disappear when the application is deleted.
- The corresponding implementation for iOS is
NSDocumentDirectory
- The corresponding implementation for Android is
AppData
Application support catalog
The application support directory is used for files that you do not want to disclose to users, that is, files that you do not want to see to users can be placed in this directory. The system will not clear the directory, and will only disappear when the application is deleted.
- The corresponding implementation for iOS is
NSApplicationSupportDirectory
- The corresponding implementation for Android is
getFilesDir()
)
Application persistent file directory
This directory is mainly a directory for storing persistent files and will not be disclosed to users. It is often used to store database files, such as sqlite.db.
External storage directory
It is mainly used to obtain external storage directories, such as SD cards, but iOS does not support external storage directories. Currently, only Android supports it.
External storage cache directory
The main user obtains the directory of application-specific external cache data, such as those with multiple storage directories on the SD card or mobile phone, but iOS does not support external storage directories, and currently only Android supports it.
External storage directory (separate partition)
The external storage directory can be obtained according to the type, such as SD card, separate partition, etc. The difference from the external storage directory is that it obtains an array of directories. However, iOS does not support external storage directories, and currently only Android supports it.
Desktop program download directory
The directory mainly used to store downloaded files, only applicable to Linux
, MacOS
, Windows
, Android
and iOS
platforms cannot be used.
path_provider method and description
method | Attributes | describe |
---|---|---|
getTemporaryDirectory() | Future<Directory> | Temporary directory |
getApplicationSupportDirectory() | Future<Directory> | Application support catalog |
getLibraryDirectory() | Future<Directory> | Application persistent file directory |
getApplicationDocumentsDirectory() | Future<Directory> | Document directory |
getExternalStorageDirectory() | Future<Directory> | External storage directory |
getExternalCacheDirectories() | Future<List<Directory>?> | External storage cache directory |
getExternalStorageDirectories() | Future<List<Directory>?> | External storage directory (separate partition) |
getDownloadsDirectory() | Future<Directory?> | Desktop program download directory |
Basic use of path_provider
Here we give a simple example, path_provider
and write the text to the file. The specific steps are as follows:
- Add dependency
- Get local directory
- Write data to disk
- Read disk data
The first step: add dependencies
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.5
Step 2: Get the local directory
Although there are a total of eight kinds of access paths, in the actual application development process, we often use three types. Let's get the paths of these three directories respectively, as follows:
/// 获取文档目录文件
Future<File> _getLocalDocumentFile() async {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/str.txt');
}
/// 获取临时目录文件
Future<File> _getLocalTemporaryFile() async {
final dir = await getTemporaryDirectory();
return File('${dir.path}/str.txt');
}
/// 获取应用程序目录文件
Future<File> _getLocalSupportFile() async {
final dir = await getApplicationSupportDirectory();
return File('${dir.path}/str.txt');
}
Step 3: Write data to disk
Here we use writeAsString()
to name
to the disk. If you need to write synchronously, you can call writeAsStringSync()
, or if you want to write by byte stream, you can call writeAsBytes()
.
String name = "Jimi";
/// 写入数据
Future<void> writeString(String str) async {
final file = await _getLocalDocumentFile();
await file.writeAsString(name);
final file1 = await _getLocalTemporaryFile();
await file1.writeAsString(name);
final file2 = await _getLocalSupportFile();
await file2.writeAsString(name);
print("写入成功");
}
Step 4: Read the disk data
try catch
is added here to prevent an abnormality in reading the file and cause a crash. We read the files in the three directories and add corresponding printing to them.
/// 读取值
Future<void> readString() async {
try {
final file = await _getLocalDocumentFile();
final result = await file.readAsString();
print("result-----$result");
final file1 = await _getLocalTemporaryFile();
final result1 = await file1.readAsString();
print("result1-----$result1");
final file2 = await _getLocalSupportFile();
final result2 = await file2.readAsString();
print("result2-----$result2");
} catch (e) {
}
}
Complete sample code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
String name = "Jimi";
/// 获取文档目录文件
Future<File> _getLocalDocumentFile() async {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/str.txt');
}
/// 获取临时目录文件
Future<File> _getLocalTemporaryFile() async {
final dir = await getTemporaryDirectory();
return File('${dir.path}/str.txt');
}
/// 获取应用程序目录文件
Future<File> _getLocalSupportFile() async {
final dir = await getApplicationSupportDirectory();
return File('${dir.path}/str.txt');
}
/// 读取值
Future<void> readString() async {
try {
final file = await _getLocalDocumentFile();
final result = await file.readAsString();
print("result-----$result");
final file1 = await _getLocalTemporaryFile();
final result1 = await file1.readAsString();
print("result1-----$result1");
final file2 = await _getLocalSupportFile();
final result2 = await file2.readAsString();
print("result2-----$result2");
} catch (e) {
}
}
/// 写入数据
Future<void> writeString(String str) async {
final file = await _getLocalDocumentFile();
await file.writeAsString(name);
final file1 = await _getLocalTemporaryFile();
await file1.writeAsString(name);
final file2 = await _getLocalSupportFile();
await file2.writeAsString(name);
print("写入成功");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text("path_provider"),),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(name,
style: TextStyle(
color: Colors.pink,
fontSize: 30
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: (){
writeString(name);
},
child: Text("存入本地目录"),
),
ElevatedButton(
onPressed: (){
readString();
},
child: Text("读取值"),
),
],
),
),
)
);
}
}
Console output
flutter: 写入成功
flutter: result-----Jimi
flutter: result1-----Jimi
flutter: result2-----Jimi
Summarize
When we need to persist data or download files, pictures or save database files, we write the files to disk, then we need to use dart:io
and path_provider
, and the path_provider
is to provide a platform-independent and consistent way to access the files of the device System, such as application temporary directory, document directory, etc.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。