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 的位置:

flutter Cannot open file, path = ‘.../test.jpg‘ (OS Error: Permission denied, errno = 13)_第1张图片

 首先在 manifest 添加权限:

    
    
    

然后在 中添加对 Android10 的访问权限:

android:requestLegacyExternalStorage="true"

如图:

flutter Cannot open file, path = ‘.../test.jpg‘ (OS Error: Permission denied, errno = 13)_第2张图片

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 createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  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开发,flutter)