Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : TextField with FocusNode does not get called when clicked outside of TextField

I have a Statefull Widget that contains a textfield. I would like to know when the user clicked outside the textfield. In order to do that I am using a FocusNode. Now the problem is my callback does not get called when a user clicks outside of the texfield. This is my code

class TestText extends State<SingleFieldEdit> 
{
    TextEditingController _qTextEditController = new TextEditingController();
    FocusNode _focus;

    TestText();

    @override
    void initState() {
        super.initState();
        _focus = new FocusNode();
        _focus.addListener(_onFocusChange);
    }

    @override
    void dispose() {
        super.dispose();
        _focus.dispose();
    }

    void _onFocusChange(){
        print("Focus changed - Does not get called when clicked outside of textbox");
        if(_focus.hasFocus==false){
            setState(() {
                _enableEdit=false;
                _qTextEditController.text = _existingText;
            });

        }
    }


    Widget getEditableField()
    {
        Widget containerBorder =  new Container(
                margin: const EdgeInsets.all(0.0),
                padding: const EdgeInsets.only(top:0.0,bottom:0.0),
                decoration: new BoxDecoration(
                    border: new Border(top:BorderSide(width: 0.4),bottom: BorderSide(width: 0.4) ),
                    ),
                child: new Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                 new Flexible(child:TextField(
                        focusNode: _focus,
                        controller: _qTextEditController,
                        decoration: InputDecoration.collapsed(hintText: 'Your hint goes here',enabled: _enableEdit),//InputDecoration(hintText: 'Your hint goes here', /*labelText: "Your Label goes here",*/ enabled: _enableEdit),
                        )),
                    getIcon(),
                    ],)
                );

        return getEditableField
    }

    @override
    Widget build(BuildContext context)
    {
        return getEditableField();
    }

}
like image 357
MistyD Avatar asked Jan 24 '19 12:01

MistyD


Video Answer


2 Answers

Wrap your Scaffold with a GestureDetector and set the onTap to Focus on another node

like image 116
Fellipe Malta Avatar answered Oct 18 '22 03:10

Fellipe Malta


You'd need to focus another FocusNode
or calling unfocus on the focused FocusNode (https://github.com/flutter/flutter/issues/19552#issuecomment-410909751)

Please follow and upvote https://github.com/flutter/flutter/issues/20227 for an easier solution (perhaps also https://github.com/flutter/flutter/issues/7247).

like image 34
Günter Zöchbauer Avatar answered Oct 18 '22 03:10

Günter Zöchbauer