3

I need help with this feature. When I enter a text in a textField, I need you to validate that text when I enter another textField.

This is my code

    class _ProfileState extends State<Profile> {
      bool _hasInputError = false;
  var idNumber = '';
  var nombreUser = "";
  FocusNode focusNode;
  void initState() {
    super.initState();
    focusNode = new FocusNode();
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
        setState(() {
          _hasInputError = idNumber.length < 3;
        });
      }
    });
  }
      @override
      Widget build(BuildContext context) {
    


        final nombreUserField = TextField(
          focusNode: _focusNode,
          onChanged: (String text) {
            nombreUser = text;
          },
        );   
        final idNumberElement = TextField(
          focusNode: _focusNode,
          decoration: InputDecoration(
            errorText: _hasInputError ? "Id is too short" : null,
            counterText: "",
          ),
          onChanged: (String tex) {
            idNumber = tex;
          },
        );
        return WillPopScope(
            child: Scaffold(
              body: Listener(
                onPointerUp: (e) {
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                child: SingleChildScrollView(
                  child: Container(child: Column(
                      children: <Widget>[
                        SizedBox(
                          height: 10,
                        ),
                        idNumberElement,
                        SizedBox(
                          height: 20,
                        ),
                        nombreUserField,
                      ],
                    ),
                  ),
                ),
              ),
            ));
      }
    }

I tried to make the validation appear in the onEditingComplete but it doesn't work. I Try this answer but it's doesn't work.

How to listen focus change in flutter?

enter image description here

Community
  • 1
  • 1
Cristian F. Bustos
  • 473
  • 1
  • 8
  • 17
  • 1
    Does this answer your question? [How to listen focus change in flutter?](https://stackoverflow.com/questions/47965141/how-to-listen-focus-change-in-flutter) – Ravinder Kumar Nov 14 '19 at 18:26
  • You can also validate on the ```blur``` event. Leaving a field fires a ```blur``` even ton that field. – Akin Okegbile Nov 14 '19 at 21:04

4 Answers4

5

initState should be out of the build function. You have declared initState inside build

  FocusNode focusNode;
  void initState() {
    super.initState();
    focusNode = new FocusNode();
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
        setState(() {
          _hasInputError = idNumber.length < 3;
        });
      }
    });
  }
  @override
  Widget build(BuildContext context){
  ..
  }

Your Code

@override
  Widget build(BuildContext context) {
    var _focusNode = FocusNode();
void initState() {
  super.initState();
  _focusNode.addListener(() {
    if (!_focusNode.hasFocus) {
      if (idNumber.length < 3) {
        "Id is too short";
      }
    }
  });
}
..
}

You should also use setState to indicate that you have changed the value of _hasInputError so that the framework might schedule a build and the user interface for this subtree might be updated to reflect the new state

You have same FocusNode object in both TextField. Remove the _focusNode from nombreUserField. FocusNode is used to identify a specific TextField in Flutter’s focus tree. Every TextField should have a different FocusNode.

Ayush Bherwani
  • 2,409
  • 1
  • 15
  • 21
1

I suppose you should add

if(!focusNode.hasfocus){
    // Do your stuff
}

Inside the focusNode listener

Amir Ali Aghamali
  • 582
  • 1
  • 7
  • 23
  • It doesn't work for me. var _focusNode = FocusNode(); void initState() { super.initState(); } _focusNode.addListener(() { if (!_focusNode.hasFocus) { if (idNumber.length < 3) "Id is too short"; } }); – Cristian F. Bustos Nov 14 '19 at 18:39
1

You need a BLoC pattern to manage this.

This is a fantastic library for BLoC, maintained by Felix

Here is the sample. This is a login screen example where we check whether the entered text is a valid email or not and password matches some specific criteria.

Though the provided sample is not the exact match that you're looking for, but you can use it as an example to manage your own state.

For Example:

  1. You enter a text in TextField1.
  2. Now you click TextField2.
  3. When the first view loses its focus
if(!firstNode.hasfocus){
    //your code
}

Fire an event.

  1. If the entered value is invalid display an appropriate error message.
Nagaraj Alagusundaram
  • 2,304
  • 2
  • 24
  • 31
0

Here we can make use of

 _formKey.currentState.validate();

where _formKey, key given to the form

 final _formKey = GlobalKey<FormState>();

and the fields has validator property defined.

e.g.

     Form(
        key: _formKey,
        child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Title',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                },
                onSaved: (value) {},
              ),
            ],
        ));
Devashish
  • 393
  • 6
  • 10
  • This does not answer the question. They were asking about validating when focusing *another* text field. – Toma Jul 19 '22 at 19:42