showFluentContextMenu function

Future<void> showFluentContextMenu({
  1. required BuildContext context,
  2. required Offset globalPosition,
  3. required List<FluentContextMenuItem> items,
})

Shows a context menu positioned at the given global position.

Implementation

Future<void> showFluentContextMenu({
  required BuildContext context,
  required Offset globalPosition,
  required List<FluentContextMenuItem> items,
}) async {
  final overlay =
      Overlay.of(context).context.findRenderObject() as RenderBox?;
  if (overlay == null) return;

  await showMenu<int>(
    context: context,
    position: RelativeRect.fromLTRB(
      globalPosition.dx,
      globalPosition.dy,
      globalPosition.dx,
      globalPosition.dy,
    ),
    items: items.asMap().entries.map((entry) {
      final item = entry.value;
      if (item.label.isEmpty && item.onPressed == null) {
        return const PopupMenuDivider() as PopupMenuEntry<int>;
      }
      return _FluentPopupMenuItem(
        value: entry.key,
        enabled: item.onPressed != null,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (item.icon != null) ...[
              Icon(item.icon, size: 20),
              const SizedBox(width: 12),
            ],
            Text(item.label),
          ],
        ),
      );
    }).toList(),
  ).then((selectedIndex) {
    if (selectedIndex != null && selectedIndex < items.length) {
      items[selectedIndex].onPressed?.call();
    }
  });
}