-
Notifications
You must be signed in to change notification settings - Fork 74
/
geolocator.dart
73 lines (68 loc) · 2.15 KB
/
geolocator.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class MyGeolocator extends StatefulWidget {
const MyGeolocator({Key? key}) : super(key: key);
@override
State<MyGeolocator> createState() => _MyGeolocatorState();
}
class _MyGeolocatorState extends State<MyGeolocator> {
String? errorMessage;
String? longitude;
String? latitude;
final TextStyle _style = const TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
);
void getCurrentPosition() async {
// Permission
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
errorMessage = 'Permission not given';
debugPrint('Permission not given');
// Requesting for accessing geolocation
await Geolocator.requestPermission();
} else {
Position currentPosition = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
longitude = currentPosition.longitude.toString();
latitude = currentPosition.latitude.toString();
debugPrint('Longitude: ${currentPosition.longitude.toString()}');
debugPrint('Latitude: ${currentPosition.latitude.toString()}');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white12,
appBar: AppBar(title: const Text('Geolocator')),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Longitude: $longitude',
style: _style,
),
Text(
'Latitude: $latitude',
style: _style,
),
const SizedBox(height: 100),
ElevatedButton(
child: const Text('Get Current Position'),
onPressed: () {
setState(() {
getCurrentPosition();
});
},
),
],
),
),
),
);
}
}