Search code examples
flutterdartlocationreal-timegeocoding

How to Implement Real-Time Live Location Tracking in Flutter Apps?


I'm developing a Flutter app that requires real-time live location tracking. My objective is to continuously track and update the user's location in real-time. However, I'm facing some issues and need guidance on how to implement this correctly.

Problem Description: Inconsistent Location Updates: I'm using the location package to get the user's coordinates and the geolocator package for geocoding. Sometimes, the location updates are inconsistent, with significant delays or inaccuracies. High Battery Consumption: Continuous location tracking seems to drain the battery quickly. I'm looking for ways to optimize battery usage while maintaining accurate real-time tracking. Best Practices and Optimization: I want to ensure that I'm following best practices for real-time location tracking in Flutter. Are there specific techniques or configurations that can improve the accuracy and efficiency of location updates?


Solution

  • import 'package:flutter/material.dart';
    import 'package:location/location.dart';
    import 'package:geolocator/geolocator.dart';
    
    class LocationPage extends StatefulWidget {
      @override
      _LocationPageState createState() => _LocationPageState();
    }
    
    class _LocationPageState extends State<LocationPage> {
      Location location = new Location();
      late LocationData _currentPosition;
      String _currentAddress = "";
    
      @override
      void initState() {
        super.initState();
        _getLocation();
      }
    
      _getLocation() async {
        bool _serviceEnabled;
        PermissionStatus _permissionGranted;
    
        _serviceEnabled = await location.serviceEnabled();
        if (!_serviceEnabled) {
          _serviceEnabled = await location.requestService();
          if (!_serviceEnabled) {
            return;
          }
        }
    
        _permissionGranted = await location.hasPermission();
        if (_permissionGranted == PermissionStatus.denied) {
          _permissionGranted = await location.requestPermission();
          if (_permissionGranted != PermissionStatus.granted) {
            return;
          }
        }
    
        location.onLocationChanged.listen((LocationData currentLocation) {
          setState(() {
            _currentPosition = currentLocation;
            _getAddressFromLatLng(_currentPosition.latitude, _currentPosition.longitude);
          });
        });
      }
    
      _getAddressFromLatLng(double? lat, double? lng) async {
        try {
          List<Placemark> placemarks = await placemarkFromCoordinates(lat!, lng!);
    
          Placemark place = placemarks[0];
    
          setState(() {
            _currentAddress = "${place.locality}, ${place.postalCode}, ${place.country}";
          });
        } catch (e) {
          print(e);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Location Example"),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                if (_currentPosition != null)
                  Text(
                    "Latitude: ${_currentPosition.latitude}, Longitude: ${_currentPosition.longitude}",
                  ),
                if (_currentAddress != "")
                  Text(
                    "Address: $_currentAddress",
                  ),
                ElevatedButton(
                  onPressed: () {
                    _getLocation();
                  },
                  child: Text("Get Location"),
                ),
              ],
            ),
          ),
        );
      }
    }