" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
or
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
to the file. The first one is more accurate but also requires more battery power. The entry should inside the <manifest>
tag but not inside the <application>
tag.
For iOS, go to ios/Runner/Info.plist
and add the following code inside the <dict>
node.
<key>NSLocationWhenInUseUsageDescription</key>
<true/>
Here is a simple code example that initializes the plugin. You can call it for example in your initState()
method of your main app state.
Future _initLocationService() async { | |
var location = Location(); | |
if (!await location.serviceEnabled()) { | |
if (!await location.requestService()) { | |
return; | |
} | |
} | |
var permission = await location.hasPermission(); | |
if (permission == PermissionStatus.denied) { | |
permission = await location.requestPermission(); | |
if (permission != PermissionStatus.granted) { | |
return; | |
} | |
} | |
var loc = await location.getLocation(); | |
print("${loc.latitude} ${loc.longitude}"); | |
} |
The following steps are performed:
Warning
If location services are disabled, you will be asked to activate them.
Warning
If usage permission has not been granted yet, you will be asked on Android. iOS will always ask on app launches. If you deny the usage, you won’t be prompted again. To change the setting, you’ll have to go to your phone settings and enable the permission for this app.
To get continouos information about position changes, you can add a listener.
location.onLocationChanged.listen((LocationData loc) {
print("${loc.latitude} ${loc.longitude}");
});
In this article, I showed you how to set up and work with location data. The configuration can be a bit tricky at first, but the possibilities of location data are endless.