0
0
Fluttermobile~20 mins

Location and GPS in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Current Location Screen
This screen shows the user's current GPS location with latitude and longitude. It has a button to fetch the location and display it on the screen.
Target UI
-------------------------
|   Current Location    |
|-----------------------|
|                       |
|  Latitude:            |
|  Longitude:           |
|                       |
|  [Get Current Location]|
-------------------------
Display latitude and longitude as text on the screen.
Add a button labeled 'Get Current Location'.
When the button is pressed, fetch the current GPS location.
Show a loading indicator while fetching location.
Handle permission requests for location access.
Show an error message if location cannot be fetched.
Starter Code
Flutter
import 'package:flutter/material.dart';

class CurrentLocationScreen extends StatefulWidget {
  @override
  State<CurrentLocationScreen> createState() => _CurrentLocationScreenState();
}

class _CurrentLocationScreenState extends State<CurrentLocationScreen> {
  String latitude = '';
  String longitude = '';
  bool isLoading = false;
  String error = '';

  // TODO: Add method to get current location

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Current Location')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Latitude: $latitude'),
            SizedBox(height: 8),
            Text('Longitude: $longitude'),
            SizedBox(height: 16),
            if (isLoading) CircularProgressIndicator(),
            if (error.isNotEmpty) Text(error, style: TextStyle(color: Colors.red)),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // TODO: Call method to get location
              },
              child: Text('Get Current Location'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class CurrentLocationScreen extends StatefulWidget {
  @override
  State<CurrentLocationScreen> createState() => _CurrentLocationScreenState();
}

class _CurrentLocationScreenState extends State<CurrentLocationScreen> {
  String latitude = '';
  String longitude = '';
  bool isLoading = false;
  String error = '';

  Future<void> _getCurrentLocation() async {
    setState(() {
      isLoading = true;
      error = '';
    });

    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() {
        error = 'Location services are disabled.';
        isLoading = false;
      });
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        setState(() {
          error = 'Location permission denied.';
          isLoading = false;
        });
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() {
        error = 'Location permissions are permanently denied.';
        isLoading = false;
      });
      return;
    }

    try {
      Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
      setState(() {
        latitude = position.latitude.toStringAsFixed(6);
        longitude = position.longitude.toStringAsFixed(6);
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        error = 'Failed to get location: $e';
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Current Location')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Latitude: $latitude'),
            SizedBox(height: 8),
            Text('Longitude: $longitude'),
            SizedBox(height: 16),
            if (isLoading) CircularProgressIndicator(),
            if (error.isNotEmpty) Text(error, style: TextStyle(color: Colors.red)),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: isLoading ? null : _getCurrentLocation,
              child: Text('Get Current Location'),
            ),
          ],
        ),
      ),
    );
  }
}

This solution uses the geolocator package to get the device's current GPS location.

First, it checks if location services are enabled. Then it requests permission if not already granted. If permission is denied or permanently denied, it shows an error message.

When permission is granted, it fetches the current position with high accuracy. The latitude and longitude are updated in the state and shown on the screen.

A loading spinner appears while fetching the location, and the button is disabled to prevent multiple requests.

If any error occurs, it is displayed in red text below the coordinates.

Final Result
Completed Screen
-------------------------
|   Current Location    |
|-----------------------|
|                       |
|  Latitude: 37.421998  |
|  Longitude: -122.0840 |
|                       |
|     [Loading...]      |
|                       |
|  [Get Current Location]|
-------------------------
User taps 'Get Current Location' button.
A loading spinner appears while the app fetches location.
After fetching, latitude and longitude numbers appear.
If location services are off or permission denied, an error message shows.
Stretch Goal
Add a map view below the coordinates that shows a marker at the current location.
💡 Hint
Use the 'google_maps_flutter' package to embed a map widget and update its camera position with the fetched coordinates.