Calling Function after clicking outside a specific TextField Flutter

Issue

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

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

Answered By – MSARKrish

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *