读写文件
使用 path_provider 包和 dart:io 库中的 File 类来实现
安装
flutter pub add path_provider
使用
import 'dart:io';
import 'package:path_provider/path_provider.dart';
// 获取应用程序文档目录的路径
Future<String> get localPath async {
// 还可通过其他方法获取对应的路径,如 getExternalStorageDirectory() 获取外部存储设备根路径,更多请查看文档
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
// 获取文件的路径
Future<File> get localFile async {
final path = await localPath;
return File('$path/data.txt');
}
// 将路径写入文件
Future<void> writeData(String data) async {
final file = await localFile;
await file.writeAsString(data);
}
// 从文件中读取数据
Future<String> readData() async {
try {
final file = await localFile;
String contents = await file.readAsString();
return contents;
} catch (e) {
return '';
}
}