path_provider
是一个Flutter
插件,主要作用是提供一种以平台无关一致的方式访问设备的文件系统,比如应用临时目录、文档目录等。而且path_provider
支持Android、iOS、Linux、MacOS、Windows。path_provider: ^2.0.11
App存储目录总共分八种:
getTemporaryDirectory()
:临时目录
NSCachesDirectory
getCacheDir
,即data/data/packageName/cache
getApplicationSupportDirectory()
:应用程序支持目录
NSApplicationSupportDirectory
getFilesDir
getLibraryDirectory()
:应用程序持久文件目录
getApplicationDocumentsDirectory()
:文档目录
NSDocumentDirectory
getDataDirectory
或getExternalStorageDirectory
,即data/data/packageName/app_flutter
getExternalStorageDirectory()
:外部存储目录
getExternalFilesDir
,即外部存储目录根目录getExternalCacheDirectories()
:外部存储缓存目录
getExternalCacheDirs
或getExternalCacheDir
getExternalStorageDirectories()
:外部存储目录(单独分区)
getExternalFilesDirs
或getExternalFilesDir
getDownloadsDirectory()
:桌面程序下载目录
Linux
、MacOS
、Windows
,Android
和iOS
平台无法使用。平时我们常用三种:getApplicationDocumentsDirectory()
、getTemporaryDirectory()
、getApplicationSupportDirectory()
。
class PathProviderDemo extends StatefulWidget {
const PathProviderDemo({Key? key}) : super(key: key);
@override
State createState() {
return _PathProviderDemoState();
}
}
class _PathProviderDemoState extends State {
late Future _tempDirectory;
late Future _appSupportDirectory;
late Future _appLibraryDirectory;
late Future _appDocumentsDirectory;
late Future _externalStorageDirectory;
late Future?> _externalStorageDirectories;
late Future?> _externalCacheDirectories;
late Future _downloadDirectory;
@override
void initState() {
super.initState();
setState(() {
_tempDirectory = getTemporaryDirectory();
_appSupportDirectory = getApplicationSupportDirectory();
_appLibraryDirectory = getLibraryDirectory();
_appDocumentsDirectory = getApplicationDocumentsDirectory();
_externalStorageDirectory = getExternalStorageDirectory();
_externalCacheDirectories = getExternalCacheDirectories();
_externalStorageDirectories = getExternalStorageDirectories();
_downloadDirectory = getDownloadsDirectory();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("path_provider支持平台"),
),
body: ListView(
children: [
_buildItem("getTemporaryDirectory", _tempDirectory),
_buildItem("getApplicationSupportDirectory", _appSupportDirectory),
_buildItem("getLibraryDirectory", _appLibraryDirectory),
_buildItem("getApplicationDocumentsDirectory", _appDocumentsDirectory),
_buildItem("getExternalStorageDirectory", _externalStorageDirectory),
_buildItem2("getExternalCacheDirectories", _externalCacheDirectories),
_buildItem2("getExternalStorageDirectories", _externalStorageDirectories),
_buildItem("getDownloadsDirectory", _downloadDirectory),
],
),
);
}
Widget _buildItem(String title, Future future) {
return Column(
children: [
Text("$title:"),
FutureBuilder(future: future, builder: _buildDirectory),
const Divider(),
],
);
}
Widget _buildItem2(String title, Future?> future) {
return Column(
children: [
Text("$title:"),
FutureBuilder(future: future, builder: _buildDirectories),
const Divider(),
],
);
}
Widget _buildDirectory(BuildContext context, AsyncSnapshot snapshot) {
Text text = const Text("");
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text("Error: ${snapshot.error}");
} else if (snapshot.hasData) {
text = Text("path: ${snapshot.data?.path}");
} else {
text = const Text("不支持");
}
}
return text;
}
Widget _buildDirectories(BuildContext context, AsyncSnapshot?> snapshot) {
Text text = const Text("2");
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text("Error: ${snapshot.error}");
} else if (snapshot.hasData) {
final String? paths = snapshot.data?.map((Directory d) => d.path).join(",");
text = Text("paths: $paths");
} else {
text = const Text("不支持");
}
}
return text;
}
}
/// 创建文件夹
createDir() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}hello/a/b/c";
print("path:$path");
var dir = Directory(path);
bool exist = dir.existsSync();
if (exist) {
print("文件已存在");
} else {
var result = dir.create(recursive: true);
print("创建$result");
}
}
Platform.pathSeparator
:平台分隔符,在Android和iOS中表示“/”。create()
:创建文件夹,默认不支持嵌套文件夹,create(recursive:true)
支持嵌套文件夹的创建。/// 遍历文件夹中的文件
queryDir() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}hello";
Stream fileList = Directory(path).list(recursive: true);
fileList.forEach((element) {
FileSystemEntityType type = FileSystemEntity.typeSync(element.path);
print("$element 类型:$type");
});
}
list()
:默认值为false,只遍历当前目录;为true时,遍历当前目录和子目录。/// 重命名文件夹
renameDir() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}hello";
var dir = Directory(path);
var newDir = await dir.rename("${parentDir.path}${Platform.pathSeparator}newhello");
print(newDir);
}
/// 删除文件夹
deleteDir() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}hello";
var dir = await Directory(path).delete(recursive: true);
print(dir);
}
delete()
:删除文件夹,默认不支持嵌套文件夹,create(recursive:true)
支持嵌套文件夹的删除。/// 创建文件
createFile() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}mytxt.txt";
var file = File(path);
bool exist = file.existsSync();
if (exist) {
print("文件已存在");
} else {
await file.create();
print(file);
}
}
file.delete();
/// 文件写入数据
writeFile() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}mytxt.txt";
var file = File(path);
await file.writeAsString("哈喽 flutter1");
//追加写入
await file.writeAsBytes(const Utf8Encoder().convert("\n哈喽 flutter2"), mode: FileMode.writeOnlyAppend);
}
/// 文件读取数据
readFile() async {
final parentDir = await getApplicationSupportDirectory();
String path = "${parentDir.path}${Platform.pathSeparator}mytxt.txt";
var file = File(path);
List lines = await file.readAsLines();
for (var e in lines) {
print(e);
}
//读取bytes并转String
String result = const Utf8Decoder().convert(await file.readAsBytes());
print("result: $result");
}
/// 读取asset文件
readAsset(BuildContext context) async {
//方式一
String jsonStr = await DefaultAssetBundle.of(context).loadString("assets/students.json");
print("jsonStr: $jsonStr");
var list = json.decode(jsonStr);
for (var e in list) {
print(e);
}
//方式二
String jsonStr2 = await rootBundle.loadString("assets/students.json");
print("jsonStr2: $jsonStr2");
}