Flutter中location插件hasPermission方法自动请求权限引发的异常问题排查
Hey there, I've run into this exact behavior with the location plugin before! The issue here is that the plugin's hasPermission() method doesn't just check the permission status—it automatically triggers a permission request if the permission is denied, which conflicts with your manual requestPermission() call and causes the double-request crash on Android. Plus, when you remove the manual request, you were worried it wouldn't wait for the user's input—but rest assured, hasPermission() does wait for the user's choice before returning the final status.
Here's how to fix your code:
Step 1: Update the Permission Check Logic
Remove the duplicate requestPermission() call, since hasPermission() already handles requesting permission when needed. Here's the revised userLocation() method:
Future<LatLng> userLocation() async{ PermissionStatus _permissionGranted; bool _serviceEnabled; _serviceEnabled = await location.serviceEnabled(); if (!_serviceEnabled) { _serviceEnabled = await location.requestService(); if (!_serviceEnabled) { return _center; } } // This line will automatically request permission if it's denied _permissionGranted = await location.hasPermission(); // No need for the manual request anymore! if (_permissionGranted != PermissionStatus.granted) { return _center; } LocationData l = await location.getLocation(); setState((){ _userLocation = LatLng(l.latitude!, l.longitude!); }); return _userLocation; }
Step 2: Verify Behavior on Android 12
With this change, you'll only get one permission prompt when the app needs it, which complies with Android's permission rules. The hasPermission() method will wait for the user to tap "Allow" or "Deny" before proceeding, so your code will correctly handle the result.
Bonus: Checking Permission Without Auto-Request
If you ever need to just check the permission status without triggering a request, check the latest location plugin docs—some versions add a parameter like requestIfDenied: false to the hasPermission() method. For now, though, the above fix will resolve your crash and permission flow issues.
内容的提问来源于stack exchange,提问作者Sveg

