Flutter is an open-source UI software development kit (SDK) developed by Google, used for creating mobile, web, and desktop applications. In this course, we will look at the TextField
widget, one of Flutter’s UI components. The TextField
is a basic widget that allows users to input text. Let’s explore the basic usage of the TextField
widget, its various features, and how to customize it in detail.
1. Basic Structure of TextField
The TextField
widget is a basic input field used to receive user input. To use it, you can create a widget with the following basic structure:
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(), // Border style for the input field
labelText: 'Text to enter', // Label text
hintText: 'Enter here', // Hint text
),
onChanged: (text) {
// Callback that is called when the text changes
print('Entered text: $text');
},
)
Here, the decoration
property defines the appearance of the input field. The labelText
defines the label for the input field, and the hintText
serves as a placeholder in the input field. The onChanged
property is a callback function that is called every time the user enters text.
2. Key Properties of the TextField Widget
The TextField
widget has several important properties that allow for finer control over the widget’s behavior and appearance. The following are the most commonly used properties:
controller
: Uses an instance ofTextEditingController
to keep track of the current state of the input field.obscureText
: Set totrue
to hide text for secure input like passwords.keyboardType
: Set the type of keyboard that pops up for an improved user experience.maxLines
: Set the maximum number of lines inputted.onSubmitted
: A callback that is called when the user completes and submits their input.
Here is how to use these properties:
TextField(
controller: myController,
obscureText: true,
keyboardType: TextInputType.emailAddress,
maxLines: 1,
onSubmitted: (value) {
print('User entered value: $value');
},
)
3. Using TextEditingController
You can use the TextEditingController
to manage data and state related to the input field. This allows you to get or set the value in the input field. Here is an example of using the TextEditingController
:
class MyTextFieldWidget extends StatefulWidget {
@override
_MyTextFieldWidgetState createState() => _MyTextFieldWidgetState();
}
class _MyTextFieldWidgetState extends State {
TextEditingController myController = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: myController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your email',
),
),
ElevatedButton(
onPressed: () {
print('Entered email: ${myController.text}');
},
child: Text('Submit'),
),
],
);
}
@override
void dispose() {
// Release the controller on widget removal to prevent memory leaks.
myController.dispose();
super.dispose();
}
}
4. Different Types of TextField
Now let’s learn about the various types of TextField
. In addition to the basic input field, there are multiple types of input fields you can customize.
4.1. Password Input Field
To create a password input field, set the obscureText
property to true
. Here is an example of a password input field:
TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your password',
),
)
4.2. Email Address Input Field
When accepting email input, set the keyboardType
to TextInputType.emailAddress
to display a dedicated keyboard for emails:
TextField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your email',
),
)
4.3. Multi-line Input Field
To support the input of multiple lines of text, set the maxLines
property:
TextField(
maxLines: 5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter content here',
),
)
5. Styling the TextField
You can style the input field to make it more beautiful and intuitive using various properties. Let’s use the properties of InputDecoration
?
fillColor
: Sets the background color of the input field.focusedBorder
: Sets the border style when the input field is focused.enabledBorder
: Sets the border style when the input field is active.errorText
: Sets the text to display in case of input errors.
An example is as follows:
TextField(
decoration: InputDecoration(
fillColor: Colors.lightBlueAccent,
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green, width: 2.0),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2.0),
),
errorText: 'Invalid input',
),
)
6. Validation and Verification of TextField
You can add a simple validation logic to check the validity of the text entered by the user. For example, you can perform basic validation for email format:
String? validateEmail(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter an email';
}
String pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$';
RegExp regex = RegExp(pattern);
if (!regex.hasMatch(value)) {
return 'Invalid email format';
}
return null;
}
TextField(
decoration: InputDecoration(
errorText: validateEmail(myController.text),
),
)
7. TextField and TextFormField
To handle input field validation and state management more efficiently, you can use the TextFormField
widget. The TextFormField
is used with the Form
widget, providing better validation and state management:
Form(
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Enter your email'),
validator: validateEmail,
),
ElevatedButton(
onPressed: () {
// submit logic
},
child: Text('Submit'),
),
],
),
)
8. TextField and FocusNode
You can use a FocusNode
to control focus on the input field. Controlling focus allows you to perform specific actions or manage input:
FocusNode myFocusNode = FocusNode();
@override
void initState() {
super.initState();
myFocusNode.addListener(() {
print('Focus state changed: ${myFocusNode.hasFocus}');
});
}
@override
Widget build(BuildContext context) {
return TextField(
focusNode: myFocusNode,
decoration: InputDecoration(labelText: 'Test focus here'),
);
}
9. Conclusion
In this tutorial, we took an in-depth look at the TextField
widget in Flutter. The TextField
is a very basic UI component that is essential in any app that requires user input. By utilizing various properties and features, we can provide a more intuitive and useful user experience.
While developing mobile and web applications using Flutter, you can enhance the user interface by leveraging the various uses of TextField
. I hope this tutorial has been helpful for your Flutter development!