Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Map -like functionality in Flutter?

Tags:

flutter

dart

I've searched quite a bit and not found a solid answer, so if this is a dupe, I honestly tried.

I have an app I'm rewriting and moving away from an html-based hybrid platform (specifically Trigger.io); doing the rewrite in Flutter and Dart, on the quick.

Part of the app includes a pretty simple screen where the user can click on an image of a human body, and via an image map, get back an identifier and caption for the body part (right forearm, left knee, head, etc).

I simply can not find an analog to this behavior and capability in Flutter. Have I missed something simple because I was totally over thinking it?

Thanks much.

like image 942
ChrisH Avatar asked Sep 15 '25 09:09

ChrisH


1 Answers

You could wrap your Image in a GestureDetector and specify onTapDown (or onTapUp) callbacks that check the tapped coordinates and act accordingly.

(To convert global coordinates to local coordinates, see: flutter : Get Local position of Gesture Detector)

Here's a rough attempt:

class ImageMap extends StatelessWidget {
  const ImageMap({
    Key key,
    @required this.image,
    @required this.onTap,
    @required this.regions,
  }) : super(key: key);

  final Widget image;
  final List<Path> regions;

  /// Callback that will be invoked with the index of the tapped region.
  final void Function(int) onTap;

  void _onTap(BuildContext context, Offset globalPosition) {
    RenderObject renderBox = context.findRenderObject();
    if (renderBox is RenderBox) {
      final localPosition = renderBox.globalToLocal(globalPosition);
      for (var (index, path) in regions.indexed) {
        if (path.contains(localPosition)) {
          onTap(index);
          return;
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (details) => _onTap(context, details.globalPosition),
      child: image,
    );
  }
}
like image 73
jamesdlin Avatar answered Sep 18 '25 09:09

jamesdlin