How do i initialize the non nullable instance in flutter - flutter

`
class Location{
late double lat;
late double lon;
void getLocation( ) async{
Position position = await _determinePosition();
lat=position.latitude;
lon=position.longitude;
}
Future<Position> _determinePosition() async {
LocationPermission permission;
permission=await Geolocator.checkPermission();
if(permission==LocationPermission.denied){
permission=await Geolocator.requestPermission();
if(permission==LocationPermission.denied){
return Future.error('Permission Denied');
}
}
return await Geolocator.getCurrentPosition();
}
}
`How to initialize the value of varibale lat and lon in this? ,
i have done everything in my reach, but it always ends with error 'Non-nullable instance field 'lon' must be initialized. (Documentation) Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'.
and if i add late than it show runtime error on my device,that late variable should be initialized.

double? lat;
double? lng;
///get location
void getLocation(pr) async {
await [
Permission.location,
].request();
if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
print('no');
}
Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high);
lat = position.latitude;
lng = position.longitude;
}

Related

Position.longitude or latitude returns null and most of the time returns nothing

Here is the code , as I mentioned most of the time it returns nothing, but once it has returned null, the permission is enabled and nothing wrong with it.
class _LoadingScreenState extends State<LoadingScreen> {
double latitude;
double longitude ;
#override
void initState() {
getLocation();
}
void getLocation() async{
Location location = new Location();
await location.getCurrentLocation();
latitude = (location.latitude);
longitude= (location.longitude);
getData();
}
void getData() async{
http.Response response = await http.get(Uri.parse('https://samples.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude &appid= $apiKey'));
if(response.statusCode == 200){
String data = response.body ;
var decodedData = jsonDecode(data);
// var longitude = decodedData["coord"]["lon"];
var weatherDescription = decodedData["weather"][0]["description"];
int id = decodedData["weather"][0]["id"];
double temp = decodedData["main"]["temp"];
String city = decodedData["name"];
print("hi");
print(id);
print(temp);
print(city);
print(latitude);
print(longitude);
}
else {
print(response.statusCode);
}
}
and here is the location class , the permission is enabled and nothing wrong with it.
import 'package:geolocator/geolocator.dart';
import 'package:flutter/material.dart';
class Location{
double latitude ;
double longitude ;
Future <void> getCurrentLocation() async{
// bool servicestatus = await Geolocator.isLocationServiceEnabled();
//
// servicestatus ? print("GPS service is enabled"): print("GPS service is disabled.");
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
latitude = position.latitude;
longitude = position.longitude;
}
catch (exception){
print(exception);
}
}
}

The method '[]' was called on null. Receiver: null Tried calling: []("main")

I have this location.dart file
class Location {
double latitude;
double longitude;
Future<void> getCurrentLocation() async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
latitude = position.latitude;
longitude = position.longitude;
} catch (e) {
print(e);
}
}
}
in another file I have
void getLocationData() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/'
'data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&'
'appid=$apiKey&units=metric');
var weatherData = await networkHelper.getData();
}
If I do not put the await location.getCurrentLocation(); I get the error The method '[]' was called on null. My question is:
If I call the Location class in the second file, why do I also need to declare the getCurrentLocation() method of this class? If I call a class don't I also activate all of its methods?

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

How to get latitude and longitude in flutter

I can figure out how to get the user's latitude and longitude together, but need to get them individually to utilise the Geolocator().distanceBetween function from the Geolocator package. My code below keeps getting the error:
Unhandled Exception: NoSuchMethodError: The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude
Future<Position> getLocation() async {
var currentLocation;
try {
currentLocation = await geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
} catch (e) {
currentLocation = null;
}
return currentLocation;
}
void calculateDistance() async {
getLocation().then((position) {
userLocation = position;
});
final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;
final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;
print(distanceInMetres);
}
Try this :
void calculateDistance() async {
getLocation().then((position) {
userLocation = position;
final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;
final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;
print(distanceInMetres);
});
}
or another way of doing this is :
void calculateDistance() async {
userLocation = await getLocation();
final double myPositionLat = userLocation.latitude;
final double myPositionLong = userLocation.longitude;
final double TPLat = 51.5148731;
final double TPLong = -0.1923663;
final distanceInMetres = await Geolocator().distanceBetween(myPositionLat, myPositionLong, TPLat, TPLong)/1000;
print(distanceInMetres);
}

NoSuchMethodError the method was called on Null

in this code below WeatherModel tried to get current location of android phone,
my problem here is once I start runing it show NoSuchMethod Found, and it says reciever is null,
as I tried a lot of debugging just to see where is my problem.
I now understand that my problem is when I create instance of Location() in WeatherModel, longitude and latitude are null, it never gets value and I dont know why...
Sorry for my bad english :(
const apiKey = 'e3653190f2b1d4803287b3074ecfe618';
const apiWeatherURL = 'https://api.openweathermap.org/data/2.5/weather';
class WeatherModel {
Future<dynamic> getLocationWeather() async {
Location location = Location();
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
var weatherData = networkHelper.getData();
return weatherData;
}
}
.....
class Location {
double latitude;
double longitude;
Future<void> getCurrentLocation() async {
try {
Position _position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
longitude = _position.longitude;
print(longitude);
latitude = _position.latitude;
print(latitude);
} catch (e) {
print(e);
}
}
}
.........
class NetworkHelper {
NetworkHelper(this.url);
final url;
Future getData() async {
http.Response response = await http.get(url);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(" Sarkawtua $data");
return data;
} else
print("Error ${response.statusCode} keshay Internet");
}
}
Because you instance fields are not updated, so they are null. You have method for getting current location but it's not fired in getLocationWeather.
Future<dynamic> getLocationWeather() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
var weatherData = await networkHelper.getData();
return weatherData;
}
Edit: You also must await networkHelper.getData() method to get not Future Object.