ali
ali

Reputation: 969

Detect any focused textfield flutter

Right now i have a list of textfield with FocusScope since i want the textfield take effect only when the text field is out of focus, below are the example of the textfield

                 FocusScope(
                  child: Focus(
                    focusNode: node,
                    onFocusChange: (focus) {
                      if (!focus) {
                        if (widget.controllers[3].text.isNotEmpty) {
                          widget.bloc.add(
                            // bloc function
                            ),
                          );
                        }
                      }
                    },
                    child: TextField(
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(30),
                        FilteringTextInputFormatter.allow(
                            RegExp('[a-zA-Z0-9]')),
                      ],
                      textCapitalization: TextCapitalization.characters,
                      hintText: '',
                      title: '',
                      editingController: widget.controllers[3],
                    ),
                  ),
                )

At the bottom of the page, there will be button to continue to the next page, however after the clicking the button i want the app to unfocus every text field first before proceed with the button onclick funtion, how do i do it? Maybe something like a function where it can detect if there's any focus on a text field

                      FlatButton(
                        padding: const EdgeInsets.symmetric(
                            vertical: 12.0, horizontal: 20.0),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                        onPressed: (){
                            _unfocus(context, state);                             
                        }
                        child: Text(
                          'Continue',
                          style: medium(
                            16,
                          ),
                        ),
                      )

unfocus funtion

void _unfocus(
  BuildContext context,
  State state,
) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus) {
    currentFocus.unfocus();
  } else {
    // go to next page function ()
  }
}

Upvotes: 0

Views: 1242

Answers (1)

YoBo
YoBo

Reputation: 2549

You can use this method to unfocus in your onPressed

  void _unfocus() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
  }

Upvotes: 1

Related Questions