Sub topic 1
Your first TextField
A TextField is a Flutter widget that lets a user enter text. It handles keyboard input, cursor movement, selection, and editing. You can place it directly in a layout such as a Column, Row, or ListView.
Prerequisites
This chapter assumes basic Dart syntax, nullable types, closures, and Flutter widgets such as Scaffold, Column, and StatefulWidget. It also assumes you can run a Flutter application.
Create a simple text field
The following app displays a label, a text field, and the text received through onChanged. The callback runs whenever the field's value changes.
import 'package:flutter/material.dart';
void main() {
runApp(const NameApp());
}
class NameApp extends StatelessWidget {
const NameApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: const Padding(
padding: EdgeInsets.all(16),
child: NameForm(),
),
),
);
}
}
class NameForm extends StatefulWidget {
const NameForm({super.key});
@override
State<NameForm> createState() => _NameFormState();
}
class _NameFormState extends State<NameForm> {
String currentName = '';
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: const InputDecoration(
labelText: 'Name',
hintText: 'Enter your name',
border: OutlineInputBorder(),
),
onChanged: (value) {
setState(() {
currentName = value;
});
},
),
const SizedBox(height: 16),
Text('Current value: $currentName'),
],
);
}
}onChanged receives a String containing the field's current text. In this example, setState stores that value in currentName and rebuilds the widget so the preview text changes.
This approach is useful for small, immediate reactions. For example, you might enable a button when text is present or filter a list while the user types. For reading or changing text from several methods, use a TextEditingController. That controller also needs a lifecycle cleanup step, which you will learn in the next chapter.
Understand the field's parts
InputDecoration controls how the field appears. A labelText identifies the field and moves above it while the field has focus or contains text. A hintText shows an example inside an empty field. A border makes the input area visible.
A TextField does not validate input by itself. It accepts text, but it does not know whether that text is required, correctly formatted, or acceptable to your application. Validation belongs to TextFormField inside a Form, which will be introduced later.
The field also receives focus when the user taps it. Flutter displays the platform keyboard automatically. When the user taps elsewhere, another widget can receive focus.
Exercise
Which callback runs when the user changes the text, and what type of value does it receive?
Show answer
The onChanged callback runs and receives the new text as a String.