Andrei Matveiakin
Andrei Matveiakin

Reputation: 1818

Showing an error under a TextField in 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.

Screenshot showing how a textfield with an error looks like

Upvotes: 2

Views: 12627

Answers (2)

user321553125
user321553125

Reputation: 3246

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*"),
),

Upvotes: 3

Haroon Ashraf Awan
Haroon Ashraf Awan

Reputation: 1219

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'
        ),
      ),

Upvotes: 9

Related Questions