Flutter Geo Locator
Admin
January 02, 2026
6 views
Step 1: Add the Dependency
Add the geolocator package to your pubspec.yaml file:
YAML
dependencies:
flutter:
sdk: flutter
geolocator: ^11.0.0 # Check pub.dev for the latest version
Step 2: Configure Permissions
You must request location permissions natively for Android and iOS.
For Android: Add this to android/app/src/main/AndroidManifest.xml inside the tag:
XML
For iOS: Add this to ios/Runner/Info.plist inside the tag:
XML
NSLocationWhenInUseUsageDescription
This app needs access to location to fill the coordinates form.
Step 3: Create the Flutter Screen
Here is the complete Dart code for the screen. It includes the text fields, the "Get GPS" logic with permission handling, and the submission function.
Dart
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LocationFormScreen extends StatefulWidget {
const LocationFormScreen({super.key});
@override
State createState() => _LocationFormScreenState();
}
class _LocationFormScreenState extends State {
final _formKey = GlobalKey();
// Controllers to manage the text inside the input fields
final TextEditingController _latController = TextEditingController();
final TextEditingController _lngController = TextEditingController();
bool _isLoading = false;
// --- 1. The function that receives the coordinates ---
void _submitCoordinates(String latitude, String longitude) {
// Replace this with your actual backend call or logic
print("Function Triggered! Sending Data:");
print("Latitude: $latitude");
print("Longitude: $longitude");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Coordinates sent: $latitude, $longitude')),
);
}
// --- 2. The GPS logic to fetch location ---
Future _fetchGPSLocation() async {
setState(() => _isLoading = true);
bool serviceEnabled;
LocationPermission permission;
// Check if location services are enabled
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
_showError('Location services are disabled.');
setState(() => _isLoading = false);
return;
}
// Check and request permissions
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
_showError('Location permissions are denied');
setState(() => _isLoading = false);
return;
}
}
if (permission == LocationPermission.deniedForever) {
_showError('Location permissions are permanently denied.');
setState(() => _isLoading = false);
return;
}
// Get the current position
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
// Update the text fields with the fetched coordinates
setState(() {
_latController.text = position.latitude.toString();
_lngController.text = position.longitude.toString();
});
} catch (e) {
_showError('Failed to get location: $e');
} finally {
setState(() => _isLoading = false);
}
}
void _showError(String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
@override
void dispose() {
_latController.dispose();
_lngController.dispose();
super.dispose();
}
// --- 3. The UI Layout ---
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Location Form')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _latController,
decoration: const InputDecoration(
labelText: 'Latitude',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty ? 'Enter latitude' : null,
),
const SizedBox(height: 16),
TextFormField(
controller: _lngController,
decoration: const InputDecoration(
labelText: 'Longitude',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty ? 'Enter longitude' : null,
),
const SizedBox(height: 24),
// Button to trigger GPS fetch
ElevatedButton.icon(
onPressed: _isLoading ? null : _fetchGPSLocation,
icon: _isLoading
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.gps_fixed),
label: Text(_isLoading ? 'Fetching...' : 'Tap to Get GPS Location'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
const SizedBox(height: 16),
// Button to submit the form
FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_submitCoordinates(_latController.text, _lngController.text);
}
},
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: const Text('Submit Coordinates'),
),
],
),
),
),
);
}
}