Read a Field With a Controller
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 24 of 34.
onChanged hears every letter. Often you only want the text when a button is pressed, like Add or Send. For that, give the field a controller:
final TextEditingController _controller = TextEditingController();
TextField(controller: _controller)The controller lives in the State, next to your other variables. It is final because it is always the same controller; only the text inside it changes. _controller.text is what the field holds right now, and _controller.clear() empties it.
void _send() {
print(_controller.text);
_controller.clear();
}A controller should be thrown away when its screen is. That is what dispose is for: Flutter calls it when the State goes away.
@override
void dispose() {
_controller.dispose();
super.dispose();
}Challenge
Medium- Add a
final TextEditingController _controllerto the State and give it to the field withcontroller:. - Make
_addshow the field's text asLast added: Buy milk, then empty the field. - Add the
disposemethod from the theory.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String _last = 'nothing';
void _add() {}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Tasks')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: const InputDecoration(
labelText: 'New task',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
ElevatedButton(onPressed: _add, child: const Text('Add')),
const SizedBox(height: 24),
Text('Last added: $_last', style: const TextStyle(fontSize: 20)),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
3Widgets With State
A Widget Class of Your OwnShow a SnackBarsetState Redraws the ScreenWrite a StatefulWidgetA Counter Up and DownHot Reload Keeps State6Text Fields
Your First Text FieldReact to TypingRead a Field With a ControllerNumbers From a Text FieldDecimals With toStringAsFixedPractice on your own: Online Flutter compiler