onSelectionChanged property

ValueChanged<int>? onSelectionChanged
final

Called when the user tapped or clicked on a shape.

The map passes the selected index to the onSelectionChanged callback but does not actually change this value until the parent widget rebuilds the maps with the new value.

This snippet shows how to use onSelectionChanged callback in SfMaps.

late List<DataModel> _data;
late MapShapeSource _mapSource;
late int _selectedIndex = -1;

@override
void initState() {
  super.initState();

  _data = <DataModel>[
    DataModel('India', 280, "Low", Colors.red),
    DataModel('United States of America', 190, "High", Colors.green),
    DataModel('Pakistan', 37, "Low", Colors.yellow),
  ];

  _mapSource = MapShapeSource.asset(
    "assets/world_map.json",
    shapeDataField: "name",
    dataCount: _data.length,
    primaryValueMapper: (int index) => _data[index].country,
    shapeColorValueMapper: (int index) => _data[index].color,
  );
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Container(
        height: 350,
        child: Padding(
          padding: EdgeInsets.only(left: 15, right: 15),
          child: Column(
            children: [
              SfMaps(
                layers: <MapLayer>[
                  MapShapeLayer(
                    source: _mapSource,
                    selectedIndex: _selectedIndex,
                    selectionSettings: MapSelectionSettings(
                      color: Colors.pink,
                    ),
                    onSelectionChanged: (int index) {
                      setState(() {
                        _selectedIndex = (_selectedIndex == index) ?
                               -1 : index;
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    ),
  );
}

class DataModel {
  const DataModel(
     this.country,
     this.usersCount,
     this.storage,
     this.color,
  );

  final String country;
  final double usersCount;
  final String storage;
  final Color color;
}

Implementation

final ValueChanged<int>? onSelectionChanged;