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