skip to Main Content

Upon starting my Flutter app it shows me the following error:

NoSuchMethodError (NoSuchMethodError: The method 'getDouble' was called on null.
Receiver: null
Tried calling: getDouble("lat"))

This is the section of the code that should be causing the error:

    _userCurrentLocationUpdate(Position updatedPosition) async {
    double distance = await Geolocator.distanceBetween(
        prefs.getDouble('lat'),
        prefs.getDouble('lng'),
        updatedPosition.latitude,
        updatedPosition.longitude);
    Map<String, dynamic> values = {
      "id": prefs.getString("id"),
      "position": updatedPosition.toJson()
    };
    if (distance >= 50) {
      if (show == Show.RIDER) {
        sendRequest(coordinates: requestModelFirebase.getCoordinates());
      }
      _userServices.updateUserData(values);
      await prefs.setDouble('lat', updatedPosition.latitude);
      await prefs.setDouble('lng', updatedPosition.longitude);
    }
  }

3

Answers


  1. getDouble returns nullable double. You can provide default value on null case.

    Geolocator.distanceBetween(
        prefs.getDouble('lat')?? .0,
        prefs.getDouble('lng')?? .0,
    

    You won’t have data until you save(first run).

    Login or Signup to reply.
  2. Your error and current code suggests that you forgot to initialize prefs variable before calling the method on it. So you need to initialize it.

    Login or Signup to reply.
  3. It is because you are passing a nullable value prefs.getDouble('lat'), but the parameter can’t be null, so you are getting this error.

    Change

    double distance = await Geolocator.distanceBetween(
            prefs.getDouble('lat'),
            prefs.getDouble('lng'),
            updatedPosition.latitude,
            updatedPosition.longitude);
    

    to

    double distance = await Geolocator.distanceBetween(
            prefs.getDouble('lat') ?? .0, //👈 Now the parameter is .0 if the getDouble is null 
            prefs.getDouble('lng') ?? .0, // You can change the default value as well.
            updatedPosition.latitude,
            updatedPosition.longitude);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search