dwyl/app

How to detect `focus` on widgets?

SimonLab opened this issue · 2 comments

At the moment to extend the TextField to take all the screen see #303 I'm using the onTap property of the widget:

          child: TextField(
            onTap: () {
              extendsFieldText();
            },

This is not ideal (tab, autofocus are two example that put focus on textfield and which aren't using onTap) and it's preferable to detect the focus on the text field instead.
Looking at learning/implementing this now.
see

Reading the TextField documentation I can see the focusNode property can be defined in the class constructor:

image

I don't know what is the keyboard focus for widget so reading the documentation find for this:
https://docs.flutter.dev/development/ui/advanced/focus

However I don't think this is directly related on how to detect focus on a widget.

After some reading it seems that we can use the Focus widget as a wrapper for the TextField:

          Focus(
            onFocusChange: (focus) {
              if (focus) {
                extendsFieldText();
              } else {
                minimizeFieldText();
              }
            },
            child: TextField(
              // onTap: () {
              //   extendsFieldText();
              // },
              decoration: const InputDecoration(
                  hintText: 'Capture what is on your mind..!.',
                  border: OutlineInputBorder()),
              expands: _expands,
              maxLines: _maxLines,
              textAlignVertical: TextAlignVertical.top,
              keyboardType: TextInputType.multiline,
            ),
          ),

The onFocusChange takes a callback where the function parameter (focus in our case) is a boolean representing if the wrapped element has the focus or not.

I'm still not sure if this is the "correct" way to detect focus, there is a lot of documentation that I haven't finished to read and there might be an edge case that I'm not aware of by using Focus or a better widget to do this.