Showing an error under a TextField in Flutter - flutter

Material design allows a text field to indicate an error via a small red label under the input box: https://material.io/components/text-fields (see screenshot below).
Is there a way to achieve this for a TextField field in Flutter? I expected this to be a property of either TextField or TextEditingController, but haven't found anything like it.

It is present in the decoration property in TextField, also you can style it using it's style property.
TextField(
decoration: InputDecoration(
errorStyle: TextStyle(),
errorText: 'Please enter something'
),
),

You show errors based on the validation results which are returned by the validator function provided by TextFormField, You check for some conditions there and return an error message or null based on what you want to show and when, or if you don't want to show anything.
child: new TextFormField(
autocorrect: false,
validator: (value) {
if (value.isEmpty) {
return 'Error Message';
}
return null;
},
onSaved: (val) => //do something...,
decoration: new InputDecoration(labelText: "Label*"),
),

Related

Flutter | How to show a Hint Text when a value is entered

I want the Hint Text to remain even when Text is entered in the TextField:
But if I give TextField something like "hintText:" in simple way, Hint Text disappears when TextField is entered:
What should I do so that the hintText doesn't disappear even when a value is entered in the TextField?
.
.
.
I tried the following:
I. I tried using the suffix widget. But it appears from the end of the TextField. (If it was possible to make the suffix widget appear after the text, I think the problem would have been solved.) :
II. Obviously Prefix Widget can't help here :
Any answers are welcome, thanks.
You can use label to be visible at the top of the TextField & the hint u can simply add below line:
floatingLabelBehavior: FloatingLabelBehavior.always
full example is given below
TextFormField(
controller: textController,
style: theme.textTheme.bodyText2,
keyboardType: keyboardType ?? TextInputType.number,
enableInteractiveSelection: false,
decoration: InputDecoration(
labelText: labelText,
labelStyle: theme.textTheme.headline6,
suffixText: suffixText ?? '',
border: OutlineInputBorder(
borderSide:
BorderSide(color: theme.textTheme.bodyText2.color, width: 2),
),
hintText: '0.0',
floatingLabelBehavior: FloatingLabelBehavior.always),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
onChanged: (String text) => onChange(text),
);

Textfields in a Row Not Aligned on Validation

I have a bottom sheet that displays a set of text fields and on there is a row with two textfields. These two textfields have validation and when one field meets the validation and the other doesn't, the textfields in this row get misaligned.
As you can see, 'Expires End' is not aligned with 'CVV' when there is a validation message showing. How can I make sure that the aligns when there is a validation message.
Just Wrap your Row With IntrinsicHeight and set alignment of Row.
IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(),
TextField()
],
),
)
You can use the settings in the decoration argument of TextField:
you can set the error text height as below in order to avoid the widget rearrangement on failed validation:
decoration: const InputDecoration(
errorStyle: TextStyle(height: 0),
)
This will keep the widget aligned, but then you have to put a Text widget somewhere, because this will mess up the layout if you return a String from your validator to show an error.
Here's an more complete example: since this was a password field of a login field, I didn't need to show an error to let the user understand that something was wrong, and the red underline that appeared was enough to let the user understand what went wrong
//...at some point in your form
TextFormField(
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
errorStyle: TextStyle(height: 0),
),
controller: pwdTec,
validator: (value) {
if (value == null || value.isEmpty || value.length < 8) {
return ""; //this will just underline the field in red
}
return null;
},
onFieldSubmitted: (_) => _formSubmit(),
),
Text(_errorMessage), //_errorMessage is a field of a StatefulWidget, that gets update by _formSubmit() with a setState() in case of errors that require an explanation
//...rest of the form

Remove error message in TextFormField in Flutter

Hi I want to remove error message caused by validator in TextFormField widget after I submit a form in flutter.
Ps : I want the error message disappeared after I select again the TextFormField to write into it again.
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null ||
value.isEmpty ||
!EmailValidator.validate(value)) {
return nullEmailMsg;
}
return null;
},
decoration: InputDecoration(
hintText: emailHint,
prefixIcon: Icon(Icons.mail),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
If you put your TextFormField inside a Form with the property autovalidateMode: AutovalidateMode.onUserInteraction, the validation function should trigger when you select again or change the text.
If the validation function is satisfied, the error message will be removed.
You have to use the autoValidateMode method in TextFormField.
Here, is the some of the reference:
https://api.flutter.dev/flutter/widgets/AutovalidateMode-class.html

Flutter - Textfield reaction when focus changes

I've made a program where the user can create an account, but I've placed some restrictions on the textfields (like for the First Name, it can only accept a string made of A-Z or a-z).
I want an "error text" to show under the textfield if the input is wrong (like if the user types "John1"), but I don't know how to do this. The simple way would be to use the onEditingComplete but this only works if the user taps on the keyboard the "done" key.
Is there a way to make the "error text" appear when the focus changes from one textfield to another?
You can use the validator property of the textfield to do this. It is recommended to encapsulate your fields in a Form() widget and then use the FormTextField() widget to implement your validations, this will enable an error to be shown at the bottom of the text field, if focus changes, or submission is attempted.
Example:
TextFormField(
onSaved: (String value) {},
validator: (String value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
)
The error will appear below in red fonts.
If you want to show error text whenever text/value changed you can do this.
In TextField 'onChanged' validate the user input using some regex and check for error ,if there is an error using TextField decoration 'errorText' property you can show required error.
Widget phoneNumberTextField() {
return Padding(
padding: EdgeInsets.fromLTRB(25, 10, 25, 10),
child: TextField(
style: TextStyle(color: Colors.white),
controller: _phoneNumberController,
maxLength: Constants.PhoneNumberTextFieldMaxLength,
onChanged: (value) {
_phoneNumberErrorText =
validatePhoneNumberTextField(_phoneNumberController.text);
_hasPhoneNumberError = _phoneNumberErrorText.isNotEmpty;
setState(() {});
},
keyboardType: TextInputType.number,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green, width: 1.0),
),
errorText: _hasPhoneNumberError ? _phoneNumberErrorText : null),
),
);
}
String validatePhoneNumberTextField(String text) {
String errorText = '';
if (text.length < 1) {
errorText = 'Phone Number should not be empty';
} else if (text.length != 10) {
errorText = 'Please enter valid phone number.';
}
return errorText;
}

in flutter form? can TextFormField and ListTile work together

in writing forms
is it good to put TextFormField inside ListTile in subtitle argument or besides each other
what the best way to write forms that need many inputs type if I want to keep the layout look like a list
[![enter image description here][1]][1]
[exampleListTile(
title: Text('Event Name'),
subtitle: TextFormField(
decoration:
InputDecoration(labelText: 'Event Name Here'),
keyboardType: TextInputType.text,
validator: (value) {
if (value.isEmpty) {
return 'Invalid Text!';
}
},
onSaved: (value) {
print(value);
},
),
),][1]
ListTile is more used in a context of a list with items os same type, but there's no rule against using the way you are doing. Like most things in flutter it's a question of preference