防止小部件树获得焦点

vov*_*ost 7 flutter flutter-layout

有没有办法防止小部件树获得焦点?

我想防止子列或任何嵌套子列(字段 1、字段 2)在不禁用字段的情况下获得焦点,字段 3应该仍然是可聚焦的。如何实现呢?

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Example'),
    ),
    body: Column(
      key: Key("Parent column"),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Column(
          key: Key("Child column"),
          children: <Widget>[
            TextField(
              key: Key("Field 1"),
            ),
            TextField(
              key: Key("Field 2"),
            )
          ],
        ),
        TextField(
          key: Key("Field 3"),
        )
      ],
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*sad 8

使用ExcludeFocus小部件,因为这也会阻止通过遍历(tab 键)获得焦点。您可能还想用 包裹小部件IgnorePointer以防止单击子树。

另请参见防止应用程序中的某些控件成为焦点


vov*_*ost 3

感谢@pskink 的建议。

这实际上是非常简单的实现:只需将小部件树包装在IgnorePointer. shouldIgnore是控制子列及其子列是否应该获得任何触摸事件的变量。

bool shouldIgnore = true;

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Example'),
    ),
     body: Column(
      key: Key("Parent column"),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        IgnorePointer(
          ignoring: shouldIgnore,
          child: Column(
            key: Key("Child column"),
            children: <Widget>[
              TextField(
                key: Key("Field 1"),
              ),
              TextField(
                key: Key("Field 2"),
              )
            ],
          ),
        ),
        TextField(
          key: Key("Field 3"),
        )
      ],
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)