Flutter GestureDetector onTap 不工作

Tom*_*uis 5 flutter flutter-layout

当用户点击外部时,尝试使用 GestureDetector 使 TextFormField 失去焦点,但我无法让它工作。onTap 永远不会触发。

class EditScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new GestureDetector(
        onTap: () {
          print('this does not fire, why???????????');

          // this is my attempt to unfocus textformfield when click away
          FocusScope.of(context).requestFocus(new FocusNode());
        },
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              TextFormField(
                maxLines: null,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ald*_*uan 4

尝试使用 Gesture Detector 包裹你的 Scaffold,然后使用 onTap 函数:

      onTap: () {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
Run Code Online (Sandbox Code Playgroud)

所以每次你点击脚手架它都会开火