简体   繁体   中英

Flutter GestureDetector onTap not working

Trying to make a TextFormField unfocus with a GestureDetector when user taps outside but I can't get it to work. onTap never fires.

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,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Try wrap your Scaffold with Gesture Detector and then onTap function:

      onTap: () {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }

So it will fire everytime you tap the scaffold

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM