圆形(Circle)用于在地图上绘制以指定经纬度为圆心、指定半径的圆,支持填充色、描边色和三种描边类型(实线/方块虚线/圆点虚线)。
本文档介绍 Circle 的创建与样式配置。
Circle(
id: 'c1',
center: const LatLng(39.9087, 116.3975),
radius: 1000, // 半径(米)
fillColor: Colors.blue.withOpacity(0.2),
strokeColor: Colors.blue,
strokeWidth: 2.0,
)
添加到地图:
TencentMap(
circles: {circle},
...
)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
id |
String? |
自动生成 | 唯一标识 |
center |
LatLng |
必填 | 圆心坐标 |
radius |
double |
必填 | 半径(米),必须 ≥ 0 |
fillColor |
Color |
Color(0x00000000)(透明) |
填充色 |
strokeColor |
Color |
Color(0xFF000000) |
描边色 |
strokeWidth |
double |
1.0 |
描边宽度(逻辑像素) |
dashPattern |
List<int>? |
null(实线) | 虚线间距,元素数量 1~2 |
borderType |
CircleBorderType |
solid |
描边类型 |
displayLevel |
int |
2 |
显示层级 |
visible |
bool |
true |
是否可见 |
zIndex |
int |
0 |
堆叠顺序 |
| 枚举值 | 说明 | dashPattern 用法 |
|---|---|---|
CircleBorderType.solid |
实线(默认) | dashPattern 不生效 |
CircleBorderType.squareDash |
方块虚线 | 需 2 个元素 [实线宽, 空白宽] |
CircleBorderType.dotDash |
圆点虚线 | 需 1 个元素 [点间距],点大小 = strokeWidth |
// 方块虚线
Circle(
center: const LatLng(39.9, 116.4),
radius: 500,
borderType: CircleBorderType.squareDash,
dashPattern: const [10, 5], // 10px 实线 + 5px 空白
strokeWidth: 2.0,
)
// 圆点虚线
Circle(
center: const LatLng(39.9, 116.4),
radius: 500,
borderType: CircleBorderType.dotDash,
dashPattern: const [8], // 点间距 8px
strokeWidth: 4.0,
)
Circle 通过 Set<Circle> 以声明式方式管理。插件在 Widget 重建时自动 diff 新旧两个 Set,计算出增/删/改三类变更并推送到原生层:
id 索引:内部用 Map<String, Circle> 索引,不依赖 Set 的 hashCode==:Circle 重写了 ==,比较 center/radius/fillColor/strokeWidth/borderType 等全部业务属性(⚠️ 也比较 onTap,但 onTap 双端均不触发,见上文已知限制)@immutable,修改属性必须用 copyWith 创建新对象final Map<String, Circle> _circles = {};
// 添加
_circles['c1'] = Circle(
id: 'c1',
center: const LatLng(39.9087, 116.3975),
radius: 1000,
);
// 更新(必须 copyWith,不能原地改字段)
_circles['c1'] = _circles['c1']!.copyWith(radius: 2000);
// 删除
_circles.remove('c1');
// 传入 Widget
TencentMap(circles: Set<Circle>.of(_circles.values));
| 错误写法 | 原因 | 正确写法 |
|---|---|---|
在同一 Set 上 add copyWith 后的对象:_circles.add(c.copyWith(radius: 2000)) |
hashCode 仅基于 id(相同),但 == 为 false(属性不同)→ Set 同时保留新旧两个对象 → diff 按 id 索引只取最后一个,行为不可预测 |
创建全新 Set,或用 Map 管理 |
两个 Circle 用同一个 id |
diff 按 id 索引成 Map 时后者覆盖前者 → 变更丢失 | 确保每个 Circle 有唯一 id(不传 id 时自动生成) |
修改了 State 变量但没调 setState |
Widget 不重建 → didUpdateWidget 不触发 → diff 不执行 |
必须在 setState 内修改变量 |
提示:Circle 的
==会比较onTap回调。如果在build方法中内联写onTap: () {},每次重建都会产生新的闭包引用 →onTap != oldOnTap→ 触发不必要的更新。建议将回调存储为成员变量或使用ValueKey稳定引用。
有帮助
没帮助