【发布时间】:2022-01-18 16:47:29
【问题描述】:
我是 Flutter 的新手,我使用 flutter_google_maps 包创建了一个谷歌地图。
我的父小部件中有以下代码,
SizedBox(
child: _showFindHouseModal
? FutureBuilder<Address?>(
future: _locationDataFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Map(
initialLatitude: _userLocation.latitude!.toDouble(),
initialLongitude: _userLocation.longitude!.toDouble(),
markers: const [],
);
}
},
)
: FutureBuilder<Address?>(
future: _showFindHouseModal,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Map( // <---------------------------------------- This one is the problem
initialLongitude: _userLocation.latitude!.toDouble(),
initialLatitude: _userLocation.latitude!.toDouble(),
markers: [
Marker(
markerId: MarkerId('${_housesList.first.id}'),
position: LatLng(_housesList.first.houseLatitude, _housesList.first.houseLongitude),
),
],
);
}
}),
),
在上面的代码中,你可以看到我使用的是三元运算符。如果_showFindHouseModal 为真,则构建Map 小部件。如果不正确,则将构建相同的 Map 小部件,但带有额外的标记。问题是,我转发的那些附加标记没有呈现在屏幕上。
不过,我想我找到了问题所在。它在子小部件中。 (就是我找不到解决问题的办法)
让我展示子小部件的代码。
class Map extends StatefulWidget {
final List<Marker> markers;
final double initialLatitude;
final double initialLongitude;
const Map({
Key? key,
required this.initialLatitude,
required this.initialLongitude,
required this.markers, // Todo: Make the default to an empty value
}) : super(key: key);
@override
State<Map> createState() => MapState();
}
class MapState extends State<Map> {
late final CameraPosition _initialCameraPosition;
late final Set<Marker> _markers = {};
final Completer<GoogleMapController> _controller = Completer();
@override
void initState() {
super.initState();
_initialCameraPosition = CameraPosition(
target: LatLng(widget.initialLatitude, widget.initialLongitude),
zoom: 12,
);
}
@override
Widget build(BuildContext context) {
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: _initialCameraPosition,
markers: _markers,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
setState(
() {
_markers.addAll(widget.markers); <--------- This is the problem I think
_markers.add(
Marker(
markerId: const MarkerId('user-marker'),
position: LatLng(widget.initialLatitude, widget.initialLongitude),
),
);
},
);
},
);
}
}
正如我在代码中指出的那样,我认为问题在于,在子小部件内部,这些标记被添加到 onMapCreated 属性下。由于地图已经在第一个FutureBuilder 中创建,因此这些标记由于某种原因没有添加到地图中。我不知道如何从第二个FutureBuilder 添加新标记。我添加的标记没有通过。
有人可以帮忙吗?我一直在努力寻找 6 个小时左右的方法,但无法成功。
【问题讨论】:
标签: flutter google-maps google-maps-markers flutter-futurebuilder flutter-state