Home > Blockchain >  Howto hide the keyboard in flutter when tapping outside of the TextField without triggering any othe
Howto hide the keyboard in flutter when tapping outside of the TextField without triggering any othe

Time:09-06

I have the case where I have something similar to this:

  • GestureDetector
    • Scaffold
      • Column
        • Button
        • TextInput

So when tapping on the TextInput, the Keyboard appears. When I do FocusScope.of(context).unfocus(); in the onTap function of the GestureDetector the keyboard hides when tapping somewhere outside of the TextField.

This is fine and the expected behavior. But my problem is when the user taps on the button while the keyboard is visible, the onPressed of the button triggers.

Is there a way so that when my TextField is focused and the keyboard is visible and the user then taps outside of the TextField that the keyboard just disappears without triggering other functions/actions (so when he taps on the button, that the onPressed does not get triggered and the keyboard disappears, and with a second tap on the button the onPressed function triggers)?

Already stuck there for a while now. Hope you can help me :)

CodePudding user response:

Wrap the scaffold with Gesture detector and on tap unfocus the focus scope

example

class Test extends StatelessWidget {
  const Test({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: const Scaffold(),
    );
  }
}

CodePudding user response:

Wrap your Scaffold Widget in a Button it can be Gesture Detector or Inkwell. Then add unfocus method in it.

GestureDetector(
  onTap: () => FocusScope.of(context).unfocus(),
  child: const Scaffold(
  body: TextFormField(
   decoration: OutlineInputBorder()),
);
  • Related