flutter Cannot open file, path = ‘.../test.jpg‘ (OS Error: Permission denied, errno = 13)
Posted 吴庆森
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter Cannot open file, path = ‘.../test.jpg‘ (OS Error: Permission denied, errno = 13)相关的知识,希望对你有一定的参考价值。
开发 flutter 遇到没权限问题,刚学不熟搞了半天,报错信息:
Cannot open file, path = '/storage/emulated/0/Download/test.jpg' (OS Error: Permission denied, errno = 13)
1. 在 androidManigfest.xml 添加需要的权限,AndroidManigfest.xml 的位置:
首先在 manifest 添加权限:
<!-- Permissions options for the `storage` group -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后在 <application> 中添加对 Android10 的访问权限:
android:requestLegacyExternalStorage="true"
如图:
2.利用 permission_handler 来申请权限
在 pubspec.yaml 添加:
permission_handler: ^5.0.1+1
包引入:
import 'package:permission_handler/permission_handler.dart';
代码中申请权限:
setPermission() async {
if (await Permission.storage.request().isGranted) { //判断是否授权,没有授权会发起授权
print("获得了授权");
setState(() {
setPhoto();
});
}else{
print("没有获得授权");
}
}
3.下面是完整代码,判断是否有权限,没有权限申请权限然后获取图片来展示,有权限直接展示图片:
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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> {
bool isPermission = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: setPhoto()
);
}
setPermission() async {
if (await Permission.storage.request().isGranted) { //判断是否授权,没有授权会发起授权
print("获得了授权");
isPermission = true;
setState(() {
setPhoto();
});
}else{
print("没有获得授权");
isPermission = false;
}
}
setPhoto() {
if(isPermission){
print("有授权");
return Center(
child:(Image.file(File('/storage/emulated/0/Download/test.jpg'),width: 100,height: 100))
);
}else{
print("申请授权");
setPermission();
return null;
}
}
}
以上是关于flutter Cannot open file, path = ‘.../test.jpg‘ (OS Error: Permission denied, errno = 13)的主要内容,如果未能解决你的问题,请参考以下文章
ImportError: libopenblas.so.0: cannot open shared object file
cannot open shared object file解决办法
xcodeproj cannot be opened because the project file cannot be parsed.
SVN cannot be opened because the project file cannot be parsed.xcode有几种可能错
Error in file(file, “rt“) : cannot open the connection In addition: Warning message:In file(file, “
Error in file(file, “rt“) : cannot open the connection In addition: Warning message:In file(file, “