You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用flutter_map时出现类型错误:LatLng无法赋值给LatLng?

Flutter Map中MapOptions.center参数类型不匹配问题解决

问题描述

使用flutter_map开发时,给MapOptions的center参数传入LatLng(51.509364, -0.128928),触发错误提示:The argument type 'LatLng' can't be assigned to the parameter type 'LatLng?'。

原因分析

flutter_map新版本中,MapOptions的center参数被定义为可空类型LatLng?,而传入的是非空的LatLng实例,导致类型不兼容。

解决方案

两种简单适配方式:

方案1:使用空断言运算符

在LatLng实例后添加!,明确告知编译器该值不为空:

center: LatLng(51.509364, -0.128928)!,

方案2:赋值给可空变量后传入

先将LatLng实例赋值给可空类型变量,再传入参数:

// 在build方法内定义
final LatLng? initialCenter = LatLng(51.509364, -0.128928);

// 在MapOptions中使用
center: initialCenter,

修改后的完整代码示例

class MapsView extends HookConsumerWidget {
  MapsView({Key? key}) : super(key: key);
  final MapController _mapController = MapController();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return FlutterMap(
      options: MapOptions(
        center: LatLng(51.509364, -0.128928)!,
        zoom: 9.2,
      ),
      layers: [
        TileLayerOptions(
          urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
          userAgentPackageName: 'com.example.app',
        ),
      ],
      nonRotatedChildren: [
        AttributionWidget.defaultWidget(
          source: 'OpenStreetMap contributors',
          onSourceTapped: null,
        ),
      ],
    );
  }
}

内容的提问来源于stack exchange,提问作者vishnu nair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:24:19