简体   繁体   中英

Validate textField when I focus on another textField

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?

在此处输入图像描述

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.

I suppose you should add

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

Inside the focusNode listener

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.

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.

eg

     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) {},
              ),
            ],
        ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM