Track user location globally in flutter (at background too) - flutter

I need to track user location at background in every screen of my app, i already implemented a method to take location with geolocator package, but it only works if i put the code in every app screen. Is it possible in flutter?
ps.: i tried to use workmanager, but the minimum interval is 15 minutes, and i need to receive the location in an interval of 3 seconds.
my actually code bellow:
getPosicaoAtual() async {
try {
Position posicao = await _posicaoAtual();
DbUtil.insert('local', {
'latitude': posicao.latitude,
'longitude': posicao.longitude,
});
_local = {
'latitude': posicao.latitude,
'longitude': posicao.longitude,
};
} catch (e) {
clearLocal();
_local['erro'] = e.toString();
}
notifyListeners();
}
Future<Position> _posicaoAtual() async {
LocationPermission permissao;
// Location location = new Location();
bool ativado = await Geolocator.isLocationServiceEnabled();
if (!ativado) {
// await location.requestService();
if (!await Geolocator.isLocationServiceEnabled()) {
return Future.error('Por favor, habilite a localização no smartphone');
}
}
permissao = await Geolocator.checkPermission();
if (permissao == LocationPermission.denied) {
permissao = await Geolocator.requestPermission();
if (permissao == LocationPermission.denied) {
return Future.error('Você precisa autorizar o acesso à localização');
}
}
if (permissao == LocationPermission.deniedForever) {
return Future.error('-1');
}
return await Geolocator.getCurrentPosition();
}

You should use https://pub.dev/packages/flutter_background_service
To run flutter code in background even app is terminated

Related

my flutter app is not taking location in real device at first time but work properly in emulator?

This code is working fine in emulator but it doesn't work properly in real device . This code for taking user location but when i open 1st time app it only ask permission for location and doesn't getlocation if restart my application then it take location.
#override
void initState() {
// TODO: implement initState
super.initState();
showAddress(context);
didChangeDependencies();
}
Future showAddress(BuildContext context) async {
await locationService();
}
void getYourAddress() {
homeServices.addAddress(
context: context,
address: address,
latitude: lat!,
logitude: long!,
locality: locality,
);
}
double? lat;
double? long;
String address = '';
String locality = '';
//For convert lat long to address
getAddress(lat, long) async {
List<geocoding.Placemark> placemarks =
await geocoding.placemarkFromCoordinates(lat, long);
if (mounted) {
setState(() {
address =
"${placemarks[0].street!} ${placemarks[0].subLocality!} ${placemarks[0].locality!} ${placemarks[0].postalCode!} ${placemarks[0].country!} ";
if (placemarks[0].locality == '') {
locality = placemarks[0].street!;
} else {
locality = placemarks[0].locality!;
}
});
}
for (int i = 0; i < placemarks.length; i++) {
print("INDEX $i ${placemarks[i]}");
}
getYourAddress();
}
Future locationService() async {
Location location = Location();
bool serviceEnabled;
PermissionStatus permissionLocation;
LocationData locData;
serviceEnabled = await location.serviceEnabled();
if (serviceEnabled == false) {
serviceEnabled = await location.requestService();
if (serviceEnabled == true) {
permissionLocation = await location.hasPermission();
if (permissionLocation == PermissionStatus.denied) {
permissionLocation = await location.requestPermission();
if (permissionLocation != PermissionStatus.granted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
}
} else if (serviceEnabled == true) {
permissionLocation = await location.hasPermission();
if (permissionLocation == PermissionStatus.denied) {
permissionLocation = await location.requestPermission();
if (permissionLocation != PermissionStatus.granted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
}
}
// Problem occuring at this point in emulator it work fine but not work in real device.
getLocation() async {
try {
LocationData locData;
Location location = Location();
locData = await location.getLocation();
if (mounted) {
setState(() {
lat = locData.latitude!;
long = locData.longitude!;
});
await getAddress(lat, long);
}
} catch (e) {
getLocation();
}
}
This code is working fine in emulator but it doesn't work properly in real device . This code for taking user location but when i open 1st time app it only ask permission for location and doesn't getlocation if restart my application then it take location.
I am expecting this app to ask user for location permission and store data imidiately to database. But it doesn't doing it on first time after i restart app then it take location . Please help me to solve this problem.
I am use Using Location and Gecoding widget of flutter. when i try ti= check logs of my app in real device it show that asynchronous suspension.

How to fix Non-nullable instance when trying to get phones location

I'm trying to get the location of my phone with geolocation however the variable that stores location when you a press the button to get location has to be store as null at the beginning as I do not have the location of the phone yet however when I do that I get an error 'Non-nullable instance field 'currentposition' must be initialized' how to I fix this
this is my code
class _HomeState extends State<Home> {
String currentAddress = 'My Address';
Position currentposition;
void initState() {}
Future<Position> _determinePosition() async {
bool serviceEnabled; //check location service is enabled
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.high);
try {
List<Placemark> placemarks =
await placemarkFromCoordinates(position.latitude, position.longitude);
Placemark place = placemarks[0];
setState(() {
currentposition = position;
currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
print(currentposition);
});
} catch (e) {
print(e);
}
throw "";
}
If you declare a variable then you also have to initialize it by passing some value to it. But in any case you want to assign value later then you can define it as late making this change to your variable you can also make it nullable by using ?
late Position currentposition; //late initialize but not null
and nullable with late
late Position? currentposition; //late initialize nullable

flutter-web: get location on web by Location plugin

I have old flutter project, I added web support to it, Now ,I am trying to get my Location in flutter web , So i added location to my page.
this is my code:
#override
void initState() {
super.initState();
_getLocation();
}
Future _getLocation() async {
Location location = new Location();
var _permissionGranted = await location.hasPermission();
_serviceEnabled = await location.serviceEnabled();
if (_permissionGranted != PermissionStatus.granted || !_serviceEnabled) {
_permissionGranted = await location.requestPermission();
_serviceEnabled = await location.requestService();
} else {
print("-----> $_serviceEnabled");
setState(() {
_serviceEnabled = true;
_loading = false;
});
}
try {
final LocationData currentPosition = await location.getLocation();
setState(() {
longitude = currentPosition.longitude.toString();
latitude = currentPosition.latitude.toString();
print(
'${widget.url}?BranchName=&latitude=${latitude}&longitude=${longitude}');
_loading = false;
});
} on PlatformException catch (err) {
_loading = false;
print("-----> ${err.code}");
}
}
After getting Location permission by chrome,
Nothing happening!
In vsCode console i just got this error:
Error: [object GeolocationPositionError]
at Object.createErrorWithStack (http://localhost:43705/dart_sdk.js:4351:12)
at Object._rethrow (http://localhost:43705/dart_sdk.js:37962:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:43705/dart_sdk.js:37956:13)
at Object._microtaskLoop (http://localhost:43705/dart_sdk.js:37788:13)
at _startMicrotaskLoop (http://localhost:43705/dart_sdk.js:37794:13)
at http://localhost:43705/dart_sdk.js:33303:9
**USING #JS('navigator.geolocation')
I also try this, but never success method called and nothing heppen.
This works now(all platforms including web), June 2021, with the Location package.
final Location location = new Location();
_locationData = await location.getLocation();
print(_locationData.latitude);
See full details here:
pub.dev/packages/location
Dart currently has an issue with the Geolocation API. Consider writing an interop library or using mine. Link below Geolocation PolyFill

If statement is being registered as a variable in my Dart Flutter code? How do I change this?

The highlighted text in the image is giving me errors like those shown in my Problems console. I've never receieved these kinds of issues when dealing with if statements, and I'm wondering why they are no registering as if statements. In one of the errors it says "if is already defined", but its not a variable. How do I solve this? Does it have anything to do with the async functions? I struggled with these
I am trying to request the user location data for a map I plan to implement in a flutter App, but it's not working :/ SOMETHING is wrong with my ifs that I can't solve.
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = new Location();
var _serviceEnabled = assignService(location);
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
}
var _permissionGranted = assignPermission(location);
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
var _locationData = assignLocation(location);
Update (code before that above):
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = Location();
var _serviceEnabled = assignService(location);
var _permissionGranted = assignPermission(location);
You wrote code outside a function.
Only variable declaration can be outside a function, not code.
For example you can do :
void StartService() {
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
}
The if shouldn't be outside code block.
You have to put it in a function. That's explain your error.
Tell me if you need more details.
Edit : just for information, the "new" keyword is not needed in flutter anymore.
Solution is very simple if can't be the member of a class you should do if checks inside a function.
void doIfChecks(){
// if statements
}
Hope this will help you.

Flutter Location package requestService() never returns

I have a function like this. Using Location package from flutter it shows the dialog to enable GPS.
Future<bool> _checkServiceStatus() async {
final Location location = Location();
bool serviceStatus = await location.serviceEnabled();
if (!serviceStatus) {
serviceStatus = await location.requestService();
print('status -> $serviceStatus');
}
return serviceStatus;
}
When its calling await location.requestService(), it is showing the dialog to enable GPS but after that it never returns the result.
Even its not executing the print() function.
What am i doing wrong here?
Any help would be very appreciated! Thanks in advance.
I had the same issue. It could be solved by upgrading your Flutter project, follow this link https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects
Try this code to check wather permission enabled, service enabled than it returns true else false. Must configure "location" package related configuration in android and ios projects.
Future<bool> checkServiceStatus() async {
final Location location = Location();
final locationPermission = await location.hasPermission();
if (locationPermission == PermissionStatus.granted) {
final locationServiceEnabled = await location.serviceEnabled();
if (locationServiceEnabled == true) {
return true;
} else {
final requestServiceStatus = await location.requestService();
if (requestServiceStatus == true) {
return true;
} else {
BotToast.showSimpleNotification(
title: "Enable GPS to allow this feature");
return false;
}
}
} else {
BotToast.showSimpleNotification(title: "Required location permission to allow this feature");
return false;
}
}