flutter阻止Widget冒泡事件

3,205 阅读1分钟

解决flutter当中嵌套Widget时触发手势点击阻止冒泡

通过网上查询到的方法添加behavior: HitTestBehavior.opaque,阻止冒泡事件,但是发现还是解决不了

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
      ),
      body: Center(
          child: GestureDetector(
            onTapDown: (detail){
              print("out click");
            },
            child: Container(
                width: 200,
                height: 200,
                color: Colors.lime,
                alignment: Alignment.center,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTapDown: (detail){
                    print("inner click");
                  },
                  child: Container(
                      width: 100,
                      height: 100,
                      color:Colors.red
                  ),
                )
            ),
          )
      )
    );
  }

我们可以使用 Stack 这个widget将两个嵌套的Widget拆分开来,这样也可以阻止冒泡

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
      ),
      body: Center(
          child: Stack(
            alignment: Alignment.center,
            children: [
              GestureDetector(
                onTapDown: (detail){
                  print("out click");
                },
                child: Container(
                    width: 200,
                    height: 200,
                    color: Colors.lime,
                    alignment: Alignment.center
                ),
              ),
              GestureDetector( // 阻止冒泡 目前还没有什么好的方法能够组织冒泡 我们可以使用Stack 将这两个Widget拆分开
                onTapDown: (detail){
                  print("inner click");
                },
                child: Container( // 当一个Container嵌套一个更小的Container时 里面的Container会自动覆盖到上一层 我们需要设置alignment 或者 将上一层的Container改Column 才会显示
                    width: 100,
                    height: 100,
                    color:Colors.red
                ),
              )
            ],
          )
      )
    );
  }