Reputation: 4478
I am using google map package on my flutter project. I have a page in which google map is shown in a full screen and carousel of products (horizontally scrollable) over it. Clicking each marker will slide carousel to reveal the product info widget.
I have following codes
CameraPosition _productLocation;
Set<Marker> markers = Set();
int _currentIndex = 0;
BitmapDescriptor defaultIcon =
BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed); //default marker
BitmapDescriptor selectedIcon =
BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueViolet); //selected marker
@override
void initState() {
super.initState();
_productLocation = CameraPosition(
target: LatLng(0, 0),
zoom: 16,
);
if (widget.productList.length > 0) {
widget.productList.asMap().forEach((index, v) {
Marker resultMarker = Marker(
icon: _currentIndex == index ? selectedIcon : defaultIcon,
consumeTapEvents: true,
markerId: MarkerId(v.slug),
position:
LatLng(double.parse(v.latitude), double.parse(v.longitude)),
onTap: () {
setState(() {
_currentIndex = index;
});
buttonCarouselController.animateToPage(index);
});
// Add it to Set
markers.add(resultMarker);
});
}
}
@override
Widget build(BuildContext context) {
size = Screen(MediaQuery.of(context).size);
return Scaffold(
backgroundColor: Colors.white,
extendBodyBehindAppBar: true,
body: Container(
width: double.infinity,
height: double.infinity,
child: GoogleMap(
markers: markers,
mapType: MapType.normal,
initialCameraPosition: _productLocation,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
),
);
Problem
The first time when we enter the page, i.e. if _currentIndex==0
, the first marker is blue in color and first product info widget is shown, rest are red color. Something that doesn't work is when I click another marker, I want this marker to turn blue and rest all red. So in short, I want selected marker to be blue. Can anybody please throw some light on it?
Thanks
Upvotes: 2
Views: 2236
Reputation: 14202
Your issue is that your markers set their color in initState()
which only happens once for the Widget. (so the setState()
fires, but the markers
Set is unchanged)
You need to move the Set<Marker> markers
population either into build()
or refactor it so that it get's re-populated from the marker onTap()
Upvotes: 2