The argument type 'double?' can't be assigned to the parameter type 'double'. dart(argument_type_not_assignable)

Viewed 12569

I'm trying to get the user current location, but I got this error on l.latitude and l.longitude

The argument type 'double?' can't be assigned to the parameter type 'double'.

void _onMapCreated(GoogleMapController _cntlr) {
    _controller = _cntlr;
    _location.onLocationChanged.listen((l) {
      _controller.animateCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            target: LatLng(l.latitude, l.longitude),
            zoom: 15,
          ),
        ),
      );
    });
  }

3 Answers

The error you get is from null-safety, the type double? means that it could be either a double, or null, but your parameter only accepts a double, and no null.

For this, you can "force" the use of 'non-null' variable by adding a ! at the end of your variable, but be careful when doing this.

CameraPosition(
    target: LatLng(l.latitude!, l.longitude!),
    zoom: 15,
)

You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety

You could also null check the local variables, thereby making your code null safe:

    when location changes
      if (lat/lon are not null) {
        animate camera
      }

So something like this might work:

  void _onMapCreated(GoogleMapController _cntlr) {
    _controller = _cntlr;
    _location.onLocationChanged.listen((l) {
      if (l.latitude != null && l.longitude != null) {
        _controller.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: LatLng(l.latitude, l.longitude),
              zoom: 15,
            ),
          ),
        );
      }
    });
  }

Logically, it wouldn't make sense to animate to a null latitude/longitude, so you can skip that listener call altogether if that's the case.

Filip talks about this situation & handling here.

The above solution did not work for me, if it did not work for you too, the problem will be because both of the variables you are trying to access must have a null check so just do this instead,

CameraPosition(
target: LatLng(l!.latitude!, l!.longitude!),
zoom: 15,

) simply add ! in front of l and another to the front of latitude or longitude, this will perfectly fix the code

Related