【问题标题】:The argument type 'double?' can't be assigned to the parameter type 'double'. dart(argument_type_not_assignable)参数类型“双?”不能分配给参数类型“双”。飞镖(argument_type_not_assignable)
【发布时间】:2021-06-25 12:52:22
【问题描述】:

我正在尝试获取用户当前位置,但在 l.latitude 和 l.longitude 上出现此错误

参数类型'double?'不能分配给参数类型“double”。

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

【问题讨论】:

    标签: flutter google-maps dart position


    【解决方案1】:

    您得到的错误来自空安全,double? 类型意味着它可以是doublenull,但您的参数只接受double,而不接受null

    为此,您可以通过在变量末尾添加! 来“强制”使用“非空”变量,但这样做时要小心。

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

    您可以在官方文档中了解更多关于 null-safety 语法和原则的信息:https://flutter.dev/docs/null-safety

    【讨论】:

      【解决方案2】:

      您还可以对局部变量进行 null 检查,从而使您的代码为 null 安全:

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

      所以这样的事情可能会起作用:

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

      从逻辑上讲,动画到零纬度/经度是没有意义的,因此如果是这种情况,您可以完全跳过该侦听器调用。

      Filip talks about this situation & handling here.

      【讨论】:

        【解决方案3】:

        上述解决方案对我不起作用,如果它对您也不起作用,问题将是因为您尝试访问的两个变量都必须进行空检查,所以只需执行此操作即可,

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

        ) 只需添加!在 l 前面,另一个在纬度或经度前面,这将完美地修复代码

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-06
          • 2021-09-15
          • 1970-01-01
          • 2021-09-30
          • 2021-09-16
          • 2021-10-03
          • 2021-09-25
          • 2019-04-23
          相关资源
          最近更新 更多