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

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

Related

Track user location globally in flutter (at background too)

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

Find Address From Coordinates

final addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
selectedAddress = addresses.first;
The plugin geocoder uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Use [geolocator][1] package and write the below code to get the city name and coordinates
void main() async {
await configureInjection(Environment.dev);
WidgetsFlutterBinding.ensureInitialized();
Position _currentPosition = await getCurrentPosition();
List<Placemark> placemarks = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = placemarks[0];
runApp(AppWidget());
}
Future<Position> getCurrentPosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
);
}

Flutter - Get user GPS location and use throughout screens globally

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),
);
}
}
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.

How do I handle a future not returning?

I'm using a location plugin to get the current location of the device. However, on certain devices, await getLocation() never returns (there are also no errors in the debug console). How do I handle such an issue?
this is my code for getCurrentLocation()
import 'package:geolocator/geolocator.dart';
import 'location.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
Position position;
await reqLocation(); // requests turn on location
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permantly denied, we cannot request permissions.');
}
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission != LocationPermission.whileInUse &&
permission != LocationPermission.always) {
return Future.error(
'Location permissions are denied (actual value: $permission).');
}
}
print('LOGIC');
position = await Geolocator.getCurrentPosition();
if (position == null) {
print('null');
} else {
print('LOCATION');
print(position);
}
return position;
}
Use a timeout for your future to handle this case: Flutter - Future Timeout
Use your future like this:
var result = await getCurrentLocation().timeout(const Duration(seconds: 5, onTimeout: () => null));
Now, your future runs for 5 seconds and if the operation is not complete yet, the future completes with null (because onTimeout returned null. You can use a different value as you like [Refer to the link above]).
Now check result. if null, the operation did not complete within specified time limit else you get your position value in result as usual if it managed to complete within the specified duration.

GPS off message, and continous location update flutter

i made an app which uses the geolocator package to check for GPS and get the location of the user, and i use the provider package to handle the state. The problem is, when the GPS is switched off, a red screen appears that says the latitude was null, i would like to implement a screen to tell the user to switch on the GPS, and update the location accordingly.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong/latlong.dart';
class MapState with ChangeNotifier {
bool locationServiceActive = true;
MapController _mapController;
MapController get mapController => _mapController;
static var _initialPosition;
var _lastPosition = _initialPosition;
LatLng get initialPosition => _initialPosition;
LatLng get lastPosition => _lastPosition;
MapState(){
checkGPS();
_getUserLocation();
}
checkGPS() async{
bool conn = await Geolocator().isLocationServiceEnabled();
if(conn == false){
locationServiceActive = false;
} else {
locationServiceActive = true;
}
notifyListeners();
}
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print("/////////////////////////////////////////////////////////////////////////////////position");
print(position);
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
}
update:-
i changed my _getUserLocation function to a stream, which works much better if the user switched on or off the gps (and it uses the last known location if the gps is off)... but it doesn't print the statement in the terminal if the position is null which is weird, only when there is lat and lng!!!
here is the modification i made...
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
StreamSubscription<Position> positionStream = geolocator.getPositionStream(locationOptions).listen(
(Position position) {
print("/////////////////////////////////////////////////////////////////////////// position");
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
If you want to notify the user about the GPS, you can use something like this
#override
void initState() {
super.initState();
initPlatformState();
location.onLocationChanged.listen((result) {
currentLocation = result;
// your code
});
});
}
void initPlatformState() async {
LocationData currentLocation;
try {
currentLocation = await location.getLocation();
error = "";
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED')
error = 'Permission Denied';
else if (e.code == 'PERMISSION_DENIED_NEVER_ASK')
error =
'Permission denied - please ask the user to enable it from the app settings';
currentLocation = null;
}
setState(() {
currentLocation = currentLocation;
});
}
Here, you are listening to the location stream if enabled. In case it is not then it throws an error. The package being used here is location