flutter:得到临时目录、下载目录等路径
一,下载第三方库:
地址:
https://pub.dev/packages/path_provider
编辑pubspec.yaml,添加path_provider
dependencies:
flutter:
sdk: flutter
path_provider: ^2.1.5
点击pub get下载
各功能支持的平台:
二,代码:
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
class PathPage extends StatefulWidget {
final Map arguments;
// 为title设置一个默认参数,这样的跳转该界面时可以不传值。
PathPage({super.key, required this.arguments});
@override
State<PathPage> createState() => _PathPageState();
}
class _PathPageState extends State<PathPage> {
Future<String> _localTempPath() async {
final directory = await getTemporaryDirectory();
return directory.path;
}
Future<String> _localDownloadPath() async {
final directory = await getDownloadsDirectory();
return directory!.path;
}
Future<String> _localDocumentPath() async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<String> _localCachePath() async {
final directory = await getApplicationCacheDirectory();
return directory.path;
}
Future<String> _localLibraryPath() async {
final directory = await getLibraryDirectory();
return directory.path;
}
Future<String> _localSupportPath() async {
final directory = await getApplicationSupportDirectory();
return directory.path;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
title: Text(widget.arguments["title"]),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
String tempDir = await _localTempPath();
print("临时路径:");
print(tempDir);
String DocumentDir = await _localDocumentPath();
print("用户生成的数据目录:");
print(DocumentDir);
String DownloadDir = await _localDownloadPath();
print("下载文件目录:");
print(DownloadDir);
String CacheDir = await _localCachePath();
print("缓存目录:");
print(CacheDir);
/* 不支持android
String LibraryDir = await _localLibraryPath();
print("应用持久存储目录:");
print(LibraryDir);
*/
String SupportDir = await _localSupportPath();
print("应用支持目录:");
print(SupportDir);
},
child: Row(
mainAxisSize: MainAxisSize.min, // 根据内容调整大小
children: <Widget>[
Icon(Icons.add), // 图标在左侧
SizedBox(width: 10), // 可选:添加一些间隔
Text("得到路径"), // 文本在右侧
],
),
),
),
);
}
}
三,测试效果:
I/flutter (25250): 临时路径:
I/flutter (25250): /data/user/0/com.example.demo3/cache
I/flutter (25250): 用户生成的数据目录:
I/flutter (25250): /data/user/0/com.example.demo3/app_flutter
I/flutter (25250): 下载文件目录:
I/flutter (25250): /storage/emulated/0/Android/data/com.example.demo3/files/downloads
I/flutter (25250): 缓存目录:
I/flutter (25250): /data/user/0/com.example.demo3/cache
I/flutter (25250): 应用支持目录:
I/flutter (25250): /data/user/0/com.example.demo3/files