Flutter - Get user GPS location and use throughout screens globally

893 views Asked by At

How can I get the user's GPS (current address) on launch and then use that throughout the app where needed? I'd like to be able to use both options of the coordinates and written address being output. I'd like to have it be string data instead of text widget, so that then I can use it in other widgets where appropriate. Here's what I have so far, but I can't figure out how to incorporate this into my app properly and extract and implement that data.

Oh, also how to make it update periodically for when then user changes locations?

Any ideas?

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

class FindMe extends StatefulWidget {
  initState() {
    FindMe();    
  }
  @override
  _FindMeState createState() => _FindMeState();
}

class _FindMeState extends State<FindMe> {
  
  String currentAddress = '';
  late Position currentposition;
  
  Future<String> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please enable Your Location Service');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(msg:'Location permissions are permanently denied, we cannot request permissions.');
    }

    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);

    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placemarks[0];
      setState(() {
        currentposition = position;
        currentAddress = "${place.locality}, ${place.postalCode}, ${place.country}";
      });    
    } catch (e) {
      print(e);
    }
    return currentAddress;
  }

  @override
  Widget build(BuildContext context) {
    _determinePosition();
    return Text(
      currentAddress,
      style: const TextStyle(color: Colors.black),           
    );
  }
}
1

There are 1 answers

0
Stefan Galler On

You could use state-management solutions like blocor riverpod to do this.

With Riverpod one solution could look like this:

class LocationService {
  Future<String> determinePosition(){...}
}

...

final locationServiceProvider = Provider((ref) => LocationService());
final positionProvider = FutureProvider((ref) => ref.watch(locationServiceProvider).determinePosition);

...

// in a consumer widget
build(BuildContext context, WidgetRef ref){
  final position = ref.watch(positionProvider);
  // do something with the position
}

You can then access the value in your position provider from different parts of your app.