Ad

The IgnorePointer Is Not Working In The GridView In Flutter

- 1 answer

class _B extends State<B>{
  ...
  // a 2*2 grid layout
  Widget _a() {
    var c = Container(
        child: GridView.count(
          crossAxisCount: 2,
          children: [_b(), _c(), _c(), _b()],
          key: ObjectKey("1"),
        ),
        width: 300,
        height: 300);
    var l = Listener(
      child: c,
      onPointerDown: (event) => print("hello"),
    );
    return l;
  }
  
  // normal widget, it's red
  Widget _b() {
    var l = Listener(
      // behavior: HitTestBehavior.deferToChild,
      onPointerDown: (event) => print(0),
      child: Listener(
        onPointerDown: (event) => print(1),
        child: Listener(
          onPointerDown: (event) => print(2),
          child: Container(
            color: Colors.red,
            height: 300,
            width: 300,
          ),
        ),
      ),
    );
    return l;
  }

  // should be ignored, it's blue
  Widget _c() {
    var l = Listener(
      // behavior: HitTestBehavior.deferToChild,
      onPointerDown: (event) => print(0),
      child: Listener(
        onPointerDown: (event) => print(1),
        child: Listener(
          onPointerDown: (event) => print(2),
          child: Container(
            color: Colors.blue,
            height: 300,
            width: 300,
          ),
        ),
      ),
    );
    var i = IgnorePointer(
      child: l,
    );
    return Listener(child: i, onPointerDown: (event) => print("3!"));
  }
}
  • when i click the red one, here is the output. it just meets my expectations.
[+1052 ms] 2
[   +1 ms] 1
[        ] 0
[   +1 ms] hello
  • But when i click the blue one, here is the output. Did't it should be ignore?How did the event be distributed to the upper widget?
[+2612 ms] hello

I have tried many methods but still not working.

here is the image, sorry for that. image

Ad

Answer

It is quite tricky here. It does actually ignore the events on the blue square, but you also have a listener on your whole GridView layout and this would be triggered always even if you create a widget that does not have a listener and add it to your GridView. My proposal is removing Listener from your top-level layout and handling everything in your widgets or components.

Widget _a() {
    var c = Container(
        child: GridView.count(
          crossAxisCount: 2,
          children: [_b(), _c(), _c(), _b()],
          key: ObjectKey("1"),
        ),
        width: 300,
        height: 300);

    return c;
}
Ad
source: stackoverflow.com
Ad