在AndroidManifest.xml中添加了READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE代码,但是依然报错FileSystemException: Cannot open file, path

动态 未结 0 231
小小草
小小草 LV1 2023年9月23日 23:40 发表
在Android 6.0及以上版本中,您需要在运行时请求读写外部存储权限。在Flutter中,您可以使用`permission_handler`包来请求权限。 以下是一个示例代码: ```dart import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { String _filePath; @override void initState() { super.initState(); _requestPermission(); } Future _requestPermission() async { if (await Permission.storage.request().isGranted) { // Permission is granted, continue with the app _getFile(); } else { // Permission is not granted, show an error message showDialog( context: context, builder: (context) => AlertDialog( title: Text('Error'), content: Text('Please grant storage permission to use this app.'), actions: [ FlatButton( child: Text('OK'), onPressed: () => Navigator.pop(context), ), ], ), ); } } Future _getFile() async { Directory picturesDir = await getExternalStorageDirectory(); String filePath = '${picturesDir.path}/Pictures/WeiXin/1.png'; File file = File(filePath); if (await file.exists()) { setState(() { _filePath = filePath; }); } else { showDialog( context: context, builder: (context) => AlertDialog( title: Text('Error'), content: Text('File not found.'), actions: [ FlatButton( child: Text('OK'), onPressed: () => Navigator.pop(context), ), ], ), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), body: Center( child: _filePath != null
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复