Calling Function after clicking outside a specific TextField Flutter

I have a form page and there are several TextFields and I want to call a function after clicking outside of one specific textfield. Is there any parameter of TextField that can serve my purpose or any way to do that?


Solution 1:

TextFormField have focusNode property, focusNode have addListener callback. which get called when TextFormField having focus and when textformfield losing its focus, with the help of focusnode we can call method when clicking outside specific textfield.

class _MyWidgetState extends State<MyWidget> {
  FocusNode firstFocusNode = FocusNode();
  FocusNode secondFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    firstFocusNode.addListener(() {
      if (!firstFocusNode.hasFocus) {
        method();
      }
    });
  }

  void method() {
    print("User clicked outside the Text Form Field");
  }

  @override
  void dispose()
  {
    firstFocusNode.removeListener((){});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(children: [
      TextFormField(focusNode: firstFocusNode),
      TextFormField(
        focusNode: secondFocusNode,
      )
    ]));
  }
}

Solution 2:

the solution you are looking for is gestureDetector, but it depends where you want to call the function if you want to call the function only when tapped inside the form area but outside the textfield then wrap the form with gesture detector and use onTap: (){}, or if you want to call the same on whole screen tapped but outside the textfield wrap it around the whole scaffold.

new Scaffold(
body: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
//this function will remove the keyboard.
},