2

I'm trying to show a menu context on a custom widget I created when it is long pressed(on tap has another behaviour).

I tried to use GestureDetector with onLongPress and use the function showMenu but it shows the menu in the corner, not over the widget pressed. I've seen a workaround to get the position of the widget and pass it to the showMenu but it looks messy to me.

 return new GestureDetector(
    child: _defaultBuild(),
    onTap: onTap,
    onLongPress: () {
      showMenu(
        items: <PopupMenuEntry>[
          PopupMenuItem(
            //value: this._index,
            child: Row(
              children: <Widget>[
                Text("Context item1")
              ],
            ),
          )
        ],
        context: context,
        position: _getPosition(context)
      );
    }
);
RelativeRect _getPosition(BuildContext context) {
  final RenderBox bar = context.findRenderObject();
  final RenderBox overlay = Overlay.of(context).context.findRenderObject();
  final RelativeRect position = RelativeRect.fromRect(
  Rect.fromPoints(
    bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
    bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
  ),
  Offset.zero & overlay.size,
);
return position;
}

I've tried also to use PopupMenuButton but I wasn't able to show the menu onLongPressed.

Any ideas?

niegus
  • 1,698
  • 4
  • 22
  • 34

1 Answers1

5

showMenu() works well on my end. It looks like the issue has something to do with how the menu is being positioned with RelativeRect. Instead of RelativeRect.fromRect(), I used RelativeRect.fromSize() on mine.

RelativeRect _getRelativeRect(GlobalKey key){
  return RelativeRect.fromSize(
      _getWidgetGlobalRect(key), const Size(200, 200));
}

Rect _getWidgetGlobalRect(GlobalKey key) {
  final RenderBox renderBox =
      key.currentContext!.findRenderObject() as RenderBox;
  var offset = renderBox.localToGlobal(Offset.zero);
  debugPrint('Widget position: ${offset.dx} ${offset.dy}');
  return Rect.fromLTWH(offset.dx / 3.1, offset.dy * 1.05,
      renderBox.size.width, renderBox.size.height);
}

Here's a complete sample that you can try.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final widgetKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: GestureDetector(
          key: widgetKey,
          child: Container(
            height: 60,
            width: 120,
            color: Colors.lightBlueAccent,
            child: const Center(child: Text('Show Menu')),
          ),
          onLongPress: () {
            showMenu(
              items: <PopupMenuEntry>[
                PopupMenuItem(
                  //value: this._index,
                  child: Row(
                    children: const [Text("Context item 1")],
                  ),
                )
              ],
              context: context,
              position: _getRelativeRect(widgetKey),
            );
          },
        ),
      ),
    );
  }

  RelativeRect _getRelativeRect(GlobalKey key){
    return RelativeRect.fromSize(
        _getWidgetGlobalRect(key), const Size(200, 200));
  }

  Rect _getWidgetGlobalRect(GlobalKey key) {
    final RenderBox renderBox =
        key.currentContext!.findRenderObject() as RenderBox;
    var offset = renderBox.localToGlobal(Offset.zero);
    debugPrint('Widget position: ${offset.dx} ${offset.dy}');
    return Rect.fromLTWH(offset.dx / 3.1, offset.dy * 1.05,
        renderBox.size.width, renderBox.size.height);
  }
}

Demo

Omatt
  • 8,564
  • 2
  • 42
  • 144