我正在寻找停止点击/单击事件的最佳方法,以免在 View 层次结构中传播。假设我们有一个简单的场景,即 TextField 装饰有一个'X'明文按钮

当我单击“X”按钮时,单击事件会传播到TextField的onPressed()。

final _textEditingController = TextEditingController(text: "");

@override
Widget build(BuildContext context) {
  return TextFormField(
    controller: _textEditingController,
    onTap: onEditTextTapped,
    decoration: InputDecoration(
      suffixIcon: IconButton(
        onPressed: onClearTextClick,
        icon: Icon(
          Icons.clear,
          size: 20.0,
        ),
      ),
    ),
    style: TextStyle(fontWeight: FontWeight.normal, fontSize: 18),
  );
}

void onEditTextTapped() {
  print('TextField tapped');
}

void onClearTextClick() {
  print('clear text clicked');
}

Flutter-防止点击事件通过 View 层次结构传递-LMLPHP

结果是:
flutter: clear text clicked
flutter: TextField tapped

我需要类似于Android的android:clickable="true"或Flutter的AbsorbPointer的东西,这些陷阱将捕获所有单击事件并仅在单击“清除文本”按钮时阻止它们传递到BUT下的 View 中。 TextFormField中的点击事件仍应触发onEditTextTapped()
Flutter( channel 稳定,v1.9.1 + hotfix.2,在Mac OS X 10.14.5 18F132上)

最佳答案

使用Stack作为选项:D

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[
        TextFormField(
          controller: _textEditingController,
          onTap: onEditTextTapped,
          decoration: InputDecoration(
            suffixIcon: IconButton(
              onPressed: onClearTextClick,
              icon: Icon(Icons.clear, size: 20.0),
            ),
          ),
          style: TextStyle(fontWeight: FontWeight.normal, fontSize: 18),
        ),
        IconButton(
          onPressed: onClearTextClick,
          icon: Icon(Icons.clear, size: 20.0),
        ),
      ],
    );
  }

10-06 08:02