CHECK location permission in flutter geolocator code example
Example 1: currunt location in flutter
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MapScreen());
class MapScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Map",
home: MapActivity(),
);
}
}
class MapActivity extends StatefulWidget {
@override
_MapActivityState createState() => _MapActivityState();
}
class _MapActivityState extends State<MapActivity> {
LatLng _center ;
Position currentLocation;
@override
void initState() {
super.initState();
getUserLocation();
}
Future<Position> locateUser() async {
return Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
getUserLocation() async {
currentLocation = await locateUser();
setState(() {
_center = LatLng(currentLocation.latitude, currentLocation.longitude);
});
print('center $_center');
}
}
Example 2: geolocation using flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}