FlutterGallery

Text Field

TextFiled can receive text information from the user.
Here are some basic uses of TextField provided by Flutter.

Basic Usage

  • TextField
  • TextFormField

There are the above types of Text Field provided by Flutter.
TextField stretches to the full width, so if you want to specify the size, use other widgets such as SizedBox.

TextField(
decoration: InputDecoration(labelText: "Standard Field"),
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: "Outlined Field"),
),

Colors

To specify the color of TextFiled, you can use OutlineInputBorder or OutlineInputBorder.
You can also change the value of focusedBorder to specify the color when focused.

TextField(
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.green),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green)),
labelText: "Outlined Field"),
),

Validation

  • TextFormField

Displaying error text in a TextField can be handled using TextFormField.
When used, it must be enclosed in a Form() and the formKey must be set.

Validation can be created freely by changing the value of validator.

final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: TextFormField(
onChanged: (text) {
_formKey.currentState!.validate();
},
initialValue: "Hello World",
validator: (value) {
if (value == "Hello World") {
return "Error!";
}
return null;
},
decoration: const InputDecoration(
labelText: "Error Field",
),
),
)

Form Control

TextEditingController() is best suited for retrieving or changing input values.

final textController = TextEditingController(text: "default value");
TextField(
controller: textController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "Control Field",
),
),

API

For further information, please refer to the official documentation below.

Previous
Next