Calling Function after clicking outside a specific TextField Flutter

139

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.
},
Share:
139
Fahmida
Author by

Fahmida

Updated on November 25, 2022

Comments

  • Fahmida
    Fahmida over 1 year

    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?

    • emanuel sanga
      emanuel sanga over 2 years
      you need a focusnode, after clicking, check if the node is unfocused and then apply your desire
    • Yeasin Sheikh
      Yeasin Sheikh over 2 years
      outside of one specific textfield can you describe it more