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;
}
}
Related
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
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
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.
I'm new to Flutter and Remote Config. In my project, I'm trying to close my ad banners from remote config like true/false statement but I think I'm missing something out. I would really appreciate if you give me any advice.
I imported remote plugin for flutter and made the android integration. After that I initialize it
Future<RemoteConfig> setupRemoteConfig() async {
final RemoteConfig remoteConfig = await RemoteConfig.instance;
// Enable developer mode to relax fetch throttling
remoteConfig.setConfigSettings(RemoteConfigSettings(debugMode: true));
await remoteConfig.activateFetched();
remoteConfig.setDefaults(<String, dynamic>{
'admob_status': 'true',
});
return remoteConfig;
}
and after that, I added it below statement to my build widget.
var value = remoteConfig.getString("admob_status");
if(value == "true"){
FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId)
.then((response) {
myBanner
..load()
..show(
//anchorOffset: 60.0,
anchorType: AnchorType.bottom);
});
} else if(value == "false") {
return null;
}
and output is "the method 'getString' was called on null."
I think I found the solution, it seems working. Maybe it can help you in the future
checkAdmobStatus() async {
final RemoteConfig remoteConfig = await RemoteConfig.instance;
final defaults = <String, dynamic>{'status': 'true'};
await remoteConfig.setDefaults(defaults);
await remoteConfig.fetch();
await remoteConfig.activateFetched();
if ('true' == remoteConfig.getString('status')) {
FirebaseAdMob.instance
.initialize(appId: FirebaseAdMob.testAppId)
.then((response) {
myBanner
..load()
..show(anchorType: AnchorType.bottom);
});
}
}
I am using
geolocator: '^3.0.1'
permission_handler: '^3.0.0'
Now I want to fetch the current location of the user and show it on the map as the user opens the Map.
So my Code is :
Future<void> requestPermission() async {
PermissionHandler()
.checkPermissionStatus(PermissionGroup.location)
.then((PermissionStatus permissionStatus) async {
print("Checking Permission " + permissionStatus.toString());
if (permissionStatus == PermissionStatus.granted) {
_getCurrentLocation();
} else {
print("Asking Permission " + permissionStatus.toString());
final List<PermissionGroup> permissions = <PermissionGroup>[
PermissionGroup.locationWhenInUse
];
final Map<PermissionGroup, PermissionStatus> permissionRequestResult =
await PermissionHandler().requestPermissions(permissions);
if (PermissionStatus.granted ==
permissionRequestResult[PermissionGroup.locationWhenInUse]) {
print("Permission Granted " + permissionStatus.toString());
_getCurrentLocation();
}
}
});
}
and permissions are defined in the manifest for android and info.list for IOS.
Now the issue is when I run this function and when it calls requestPermission function, it shows the popup asking for the permission and
when I allow the permission app crashes with an error :
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions: ... java.lang.IllegalStateException: Reply already submitted
and also the result of permission is Permission.disabled though I allowed the permission in application settings and in permission it shows that location is permission is allowed. but I tried opening app several times it shows Permission.disabled.
and even if I deny the app crashes with the same error.
So what I have concluded is :
If I allow or deny it crashes because it is requesting multiple times and even if I allow the result is Permission.disabled.
Link for the video: https://youtu.be/A1DKkw6u4HI
Can anyone help me solving this issue?
Or please tell me how to take the current location map easily
please tell me how to take the current location map easily
If you just need to fetch current location easily and you just need location permission then :
you can use location plugin with flutter :
In your pubspec.yml : location : ^2.3.0
Then for fetching Current location :
Import location Package
import 'package:location/location.dart' as locationPackage;
Add this to your State
locationPackage.Location _locationService = new locationPackage.Location();
bool _permission = false;
Call this function in initState or whenever you need current Location
fetchCurrentLocation() async {
await _locationService.changeSettings(
accuracy: locationPackage.LocationAccuracy.HIGH, interval: 1000);
locationPackage.LocationData location;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
bool serviceStatus = await _locationService.serviceEnabled();
print("Service status: $serviceStatus");
if (serviceStatus) {
_permission = await _locationService.requestPermission();
print("Permission: $_permission");
if (_permission) {
location = await _locationService.getLocation();
print("Location: ${location.latitude}");
}
} else {
bool serviceStatusResult = await _locationService.requestService();
print("Service status activated after request: $serviceStatusResult");
if (serviceStatusResult) {
fetchCurrentLocation();
}
}
} on PlatformException catch (e) {
print(e);
if (e.code == 'PERMISSION_DENIED') {
//error = e.message;
} else if (e.code == 'SERVICE_STATUS_ERROR') {
//error = e.message;
}
location = null;
}
}