In Flutter, how can a positioned Widget feel taps outside of its parent Stack area?

后端 未结 3 589
既然无缘
既然无缘 2021-01-02 02:52

A Stack contains MyWidget inside of a Positioned.

Stack(
  overflow: Overflow.visible,
  children: [
    Positioned(
          


        
3条回答
  •  失恋的感觉
    2021-01-02 03:16

    Ok, I did a workaround about this, basically I added a GestureDetector on the parent and implemented the onTapDown. Also you have to keep track your Widget using GlobalKey to get the current position.

    When the Tap at the parent level is detected check if the tap position is inside your widget.

    The code below:

    final GlobalKey key = new GlobalKey();
    
          void onTapDown(BuildContext context, TapDownDetails details) {
            final RenderBox box = context.findRenderObject();
            final Offset localOffset = box.globalToLocal(details.globalPosition);
            final RenderBox containerBox = key.currentContext.findRenderObject();
            final Offset containerOffset = containerBox.localToGlobal(localOffset);
            final onTap = containerBox.paintBounds.contains(containerOffset);
            if (onTap){
              print("DO YOUR STUFF...");
            }
          }
    
          @override
          Widget build(BuildContext context) {
            return GestureDetector(
              onTapDown: (TapDownDetails details) => onTapDown(context, details),
              child: Container(
                color: Colors.red,
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                child: Align(
                  alignment: Alignment.topLeft,
                          child: SizedBox(
                    width: 200.0,
                    height: 400.0,
                    child: Container(
                      color: Colors.black,
                        child: Stack(
                          overflow: Overflow.visible,
                          children: [
                            Positioned(
                              top: 0.0, left: 0.0,
                                              child: Container(
                                key: key,
                                width: 500.0,
                                height: 200.0,
                                color: Colors.blue,
                              ),
                            ),
                          ],
                        ),
    
                    ),
                  ),
                ),
              ),
            );
          } 
    

提交回复
热议问题