文件系统异常(文件系统异常:无法打开文件,路径 =(操作系统错误:权限被拒绝,errno = 13))重新安装 Flutter 应用程序时



当我重新安装应用程序时,当我试图读取已经使用flutter应用程序创建的外部文件时,我有一个奇怪的行为。读写工作很好,但当我卸载应用程序并再次运行它时,它给了我FileSystemException。我创建了一个非常简单的例子来演示这个问题。我真的卡住了,想不出解决办法了!

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _message = '';
String _content = '';
void _writeFile() {
setState(() {
File file = File('/storage/emulated/0/Documents/test2.txt');
if (file.existsSync()) {
_message = 'File already exsists';
_content = '';
} else {
String fileContent = '{"key","value"}';
file.writeAsString(fileContent);
_message = 'File created';
_content = fileContent;
}
});
}
Future<void> _readFile() async {
{
File file = File('/storage/emulated/0/Documents/test2.txt');
if (!file.existsSync()) {
_message = 'File is not there!';
} else {
_message = 'File read :';
_content = await file.readAsString();
}
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_message),
const Text(''),
Text(_content),
],
),
),
floatingActionButton: Row(
children: [
const SizedBox(width: 100),
FloatingActionButton(
onPressed: _writeFile,
tooltip: 'Write',
child: const Text('Write'),
),
const SizedBox(width: 100),
FloatingActionButton(
onPressed: _readFile,
tooltip: 'Read',
child: const Text('Read'),
),
],
),
);
}
}

输入图片描述

这个问题可能与Android/iOS的权限系统有关。看看这个包裹,我想它会解决你的问题。

permission_handler

您需要添加如下内容:

var status = await Permission.storage.status;
if (status.isDenied) {
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
].request();
} else {
// Your method calls here
}

相关内容