如何在Dart中无需Method Channel申请WRITE_EXTERNAL_STORAGE权限?
Hey there! I get you want to handle storage permissions purely in Dart without touching Method Channels or writing native Java code—let's break this down with a straightforward solution using Flutter's go-to permission handling package.
Step 1: Add the permission_handler Dependency
This package abstracts all native permission logic behind a clean Dart API, so you don't need to write any Java/Kotlin code yourself. Add it to your pubspec.yaml:
dependencies: permission_handler: ^10.2.0 # Use the latest version available
Step 2: Confirm Your AndroidManifest Configuration
You already added the permission, but just a quick note for compatibility:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- For Android 10+, if you need to bypass scoped storage, add this too (optional): --> <application android:requestLegacyExternalStorage="true"> ... </application>
Step 3: Implement Permission Request in Dart
Here's a complete function to request storage permission, check its status, and handle different outcomes:
import 'package:permission_handler/permission_handler.dart'; Future<void> requestStoragePermission() async { // Request the storage permission final PermissionStatus status = await Permission.storage.request(); switch (status) { case PermissionStatus.granted: // Permission is granted—proceed with your storage operations print("WRITE_EXTERNAL_STORAGE permission granted!"); break; case PermissionStatus.denied: // Permission was denied temporarily—you can ask again later print("Permission denied. You can request it again."); break; case PermissionStatus.permanentlyDenied: // Permission was permanently denied—direct user to app settings print("Permission permanently denied. Please enable it in app settings."); await openAppSettings(); // Opens the app's settings page break; default: break; } }
Key Notes for Android Versions
- Android 13+: The
WRITE_EXTERNAL_STORAGEpermission is deprecated and split into granular permissions likeREAD_MEDIA_IMAGES,READ_MEDIA_VIDEO, etc. Thepermission_handlerpackage automatically handles this—callingPermission.storagewill request the appropriate permissions based on the Android version. - Scoped Storage: If you're targeting Android 10 (API 29) or higher, consider using scoped storage instead of relying on
WRITE_EXTERNAL_STORAGEfor better compliance, but the above code still works if you need the legacy access.
This approach keeps everything in Dart, no native code required, and covers all common permission scenarios.
内容的提问来源于stack exchange,提问作者Anil8753

