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

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?

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

How do i initialize the non nullable instance in 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;
}

Flutter - <asynchronous suspension> with geocoder package

I need to get the city name from Longitude and Latitude.
I do not found a single package to do that, so I use location package to get Long and Lat and used geocoder to get the city name.
But I keep have this error and have no result :
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(failed, Failed, null, null)
and this one after it on the console: < asynchronous suspension >
Here is my code :
class _ProfileScreenState extends State<ExploreScreen> {
dynamic currentLocation;
double userLongitude;
double userLatitude;
Coordinates coordinates;
var addresses;
var first;
#override
initState() {
super.initState();
_getCurrentLongAndLat();
_getCurrentPosition(userLatitude, userLatitude);
}
Future _getCurrentLongAndLat() async {
currentLocation = LocationData;
var error;
var location = new Location();
try {
currentLocation = await location.getLocation();
userLatitude = currentLocation.latitude;
userLongitude = currentLocation.longitude;
print('$userLatitude $userLatitude');
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
}
currentLocation = null;
}
}
Future _getCurrentPosition(double long, double lat) async {
coordinates = new Coordinates(userLatitude, userLongitude);
addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
print(addresses.first);
}
}
I realized flutter packages geolocator and location conflict with each other sometimes.
Try using geolocator to get your current position:
Future _getCurrentPosition() async {
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((Position position) {
setState(() {
_currentPosition = position;
userLongitude = position.longitude;
userLatitude = position.latitude;
});
});
}
It is a Future, so you can use await to really wait for results and after that call the getAddress function with the userLat and userLng.

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.