select_form_field插件是通过使用Overlay组件来实现弹窗显示在点击的位置的。

首先,需要在点击事件中获取点击位置的相对于屏幕的坐标位置。可以使用GestureDetector组件来监听用户的点击事件,然后使用GlobalKey获取OverlayState对象,通过OverlayState对象创建一个OverlayEntry。

然后,需要将弹窗的位置设置为点击位置的偏移量,可以使用Positioned组件将弹窗的位置设置为相对于屏幕的偏移量。

最后,将弹窗添加到Overlay中即可显示在点击位置。当弹窗关闭时,需要将OverlayEntry从Overlay中移除。

以下是示例代码:

class MyWidget extends StatelessWidget {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<State<StatefulWidget>> _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        final RenderBox renderBox =
            _key.currentContext.findRenderObject() as RenderBox;
        final offset = renderBox.localToGlobal(Offset.zero);
        _showDialog(context, offset);
      },
      child: Container(
        key: _key,
        child: Text('Click me'),
      ),
    );
  }

  void _showDialog(BuildContext context, Offset offset) async {
    OverlayState overlayState = Overlay.of(context);
    OverlayEntry overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
          left: offset.dx,
          top: offset.dy,
          child: Form(
            key: _formKey,
            child: AlertDialog(
              title: Text('Select an option'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    RadioListTile(
                      title: Text('Option 1'),
                      value: 1,
                      groupValue: _selectedOption,
                      onChanged: (value) {
                        _selectedOption = value;
                        Navigator.of(context).pop();
                      },
                    ),
                    RadioListTile(
                      title: Text('Option 2'),
                      value: 2,
                      groupValue: _selectedOption,
                      onChanged: (value) {
                        _selectedOption = value;
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
    overlayState.insert(overlayEntry);
    await Future.delayed(Duration(seconds: 5));
    overlayEntry.remove();
  }
}
Flutter下select_form_field插件是如何让弹窗显示在点击的位置的

原文地址: https://www.cveoy.top/t/topic/9oX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录