Get device current location in flutter using location package
Get device current location in flutter#
Getting device location in flutter is fairly easy. Most of the apps required user’s current location if you are building any location based apps may be you also need to get the user’s current location.
for getting location there is package in flutter.
first add this package in pubspec.yaml
file under dependency.
now run flutter pub get
which will download that package. in most of the IDE it auto downloads when added into pubspec.
pubspec.yaml
dependencies:
flutter:
sdk: flutter
location: ^4.3.0
version of package you can tweak based on you projects flutter version.
now create a new file in helper folder.
file name is like location_helper.dart
content of the file will be like below.
location_helper.dart
import 'package:location/location.dart';
Future<LocationData?> getLocation() async {
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
print("service not enabled");
return null;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
print("permission dened");
return null;
}
}
_locationData = await location.getLocation();
return _locationData;
}
now anywhere in your application you can call this getLocation()
function which will return latitude and longitude of device.
it will auto ask for location permission.
for using this function look below code.
LocationData? locData = await getLocation();
print(locData?.latitude);
print(locData?.longitude);