在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